import { eq } from "drizzle-orm";
import { type Response, Router } from "express";

import { db } from "../db/db.controller.js";
import { notifications } from "../db/schema/notifications.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 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
			},
		},
	});

	const { data: nName, error: nError } = await tryCatch(
		db
			.select()
			.from(notifications)
			.where(
				!hasPermissions.success ? eq(notifications.active, true) : undefined,
			)
			.orderBy(notifications.name),
	);

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

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