import { z } from "zod";
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { getUserNotifications, markNotificationsAsRead, getUnreadNotificationCount } from "@/lib/notifications";

const app = new Hono()
  .get(
    "/",
    zValidator(
      "query",
      z.object({
        workspaceId: z.string().optional(),
      })
    ),
    async (c) => {
      const session = await auth();
      const { workspaceId } = c.req.valid("query");

      if (!session?.user?.email) {
        return c.json({ error: "Unauthorized" }, 401);
      }

      const currentUser = await prisma.user.findUnique({
        where: { email: session.user.email },
      });

      if (!currentUser) {
        return c.json({ error: "User not found" }, 404);
      }

      try {
        const notifications = await getUserNotifications(currentUser.id, workspaceId);
        return c.json({ data: notifications });
      } catch (error) {
        console.error("Failed to fetch notifications:", error);
        return c.json({ error: "Failed to fetch notifications" }, 500);
      }
    }
  )
  .patch(
    "/mark-read",
    zValidator(
      "json",
      z.object({
        notificationIds: z.array(z.string()),
      })
    ),
    async (c) => {
      const session = await auth();
      const { notificationIds } = c.req.valid("json");

      if (!session?.user?.email) {
        return c.json({ error: "Unauthorized" }, 401);
      }

      const currentUser = await prisma.user.findUnique({
        where: { email: session.user.email },
      });

      if (!currentUser) {
        return c.json({ error: "User not found" }, 404);
      }

      try {
        await markNotificationsAsRead(notificationIds);
        return c.json({ success: true });
      } catch (error) {
        console.error("Failed to mark notifications as read:", error);
        return c.json({ error: "Failed to mark notifications as read" }, 500);
      }
    }
  )
  .get(
    "/unread-count",
    zValidator(
      "query",
      z.object({
        workspaceId: z.string().optional(),
      })
    ),
    async (c) => {
      const session = await auth();
      const { workspaceId } = c.req.valid("query");

      if (!session?.user?.email) {
        return c.json({ error: "Unauthorized" }, 401);
      }

      const currentUser = await prisma.user.findUnique({
        where: { email: session.user.email },
      });

      if (!currentUser) {
        return c.json({ error: "User not found" }, 404);
      }

      try {
        const count = await getUnreadNotificationCount(currentUser.id, workspaceId);
        return c.json({ data: { count } });
      } catch (error) {
        console.error("Failed to get unread count:", error);
        return c.json({ error: "Failed to get unread count" }, 500);
      }
    }
  );

export default app; 