import { eq } from "drizzle-orm";
import { type Response, Router } from "express";
import { db } from "../db/db.controller.js";
import { notificationSub } from "../db/schema/notifications.sub.schema.js";
import { auth } from "../utils/auth.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const r = Router();

r.get("/", async (req, res: Response) => {
	const { userId } = req.query;

	const hasPermissions = await auth.api.userHasPermission({
		body: {
			//userId: req?.user?.id,
			role: req.user?.roles as any,
			permissions: {
				notifications: ["readAll"], // This must match the structure in your access control
			},
		},
	});

	if (userId) {
		hasPermissions.success = false;
	}

	const { data, error } = await tryCatch(
		db
			.select()
			.from(notificationSub)
			.where(
				!hasPermissions.success
					? eq(notificationSub.userId, `${req?.user?.id ?? ""}`)
					: undefined,
			),
	);

	if (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "notification",
			subModule: "post",
			message: `There was an error getting subscriptions `,
			data: [error],
			status: 400,
		});
	}

	return apiReturn(res, {
		success: true,
		level: "info",
		module: "notification",
		subModule: "post",
		message: `Subscriptions`,
		data: data ?? [],
		status: 200,
	});
});
export default r;
