import { and, eq } from "drizzle-orm";
import { type Response, Router } from "express";
import z from "zod";
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";
import { modifiedNotification } from "./notification.controller.js";

const newSubscribe = z.object({
	userId: z.string().describe("User id."),
	notificationId: z.string().describe("Notification id"),
});

const r = Router();

r.delete("/", 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
			},
		},
	});

	try {
		const validated = newSubscribe.parse(req.body);

		const { data, error } = await tryCatch(
			db
				.delete(notificationSub)
				.where(
					and(
						eq(
							notificationSub.userId,
							hasPermissions ? validated.userId : (req?.user?.id ?? ""),
						), // allows the admin to delete this
						//eq(notificationSub.userId, req?.user?.id ?? ""),
						eq(notificationSub.notificationId, validated.notificationId),
					),
				)
				.returning(),
		);

		await modifiedNotification(validated.notificationId);

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

		if (data.length <= 0) {
			return apiReturn(res, {
				success: false,
				level: "info",
				module: "notification",
				subModule: "post",
				message: `Subscription was not deleted invalid data sent over`,
				data: data ?? [],
				status: 200,
			});
		}

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "notification",
			subModule: "post",
			message: `Subscription deleted`,
			data: data ?? [],
			status: 200,
		});
	} catch (err) {
		if (err instanceof z.ZodError) {
			const flattened = z.flattenError(err);
			// return res.status(400).json({
			// 	error: "Validation failed",
			// 	details: flattened,
			// });

			return apiReturn(res, {
				success: false,
				level: "error", //connect.success ? "info" : "error",
				module: "routes",
				subModule: "notification",
				message: "Validation failed",
				data: [flattened.fieldErrors],
				status: 400, //connect.success ? 200 : 400,
			});
		}
	}
});
export default r;
