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 { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";
import { modifiedNotification } from "./notification.controller.js";

const newSubscribe = z.object({
	emails: z
		.email()
		.array()

		.describe("An array of emails"),
	userId: z.string().describe("User id."),
	notificationId: z
		.string()

		.describe("Notification id"),
});

const r = Router();

r.post("/", async (req, res: Response) => {
	try {
		const validated = newSubscribe.parse(req.body);

		const emails = validated.emails
			.map((e) => e.trim().toLowerCase())
			.filter(Boolean);

		const uniqueEmails = [...new Set(emails)];

		const { data, error } = await tryCatch(
			db
				.insert(notificationSub)
				.values({
					userId: req?.user?.id ?? "",
					notificationId: validated.notificationId,
					emails: uniqueEmails,
				})
				.onConflictDoUpdate({
					target: [notificationSub.userId, notificationSub.notificationId],
					set: { emails: uniqueEmails },
				})
				.returning(),
		);

		await modifiedNotification(validated.notificationId);

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

		return apiReturn(res, {
			success: true,
			level: "info",
			module: "notification",
			subModule: "post",
			message: `Subscribed to notification`,
			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;
