import { NextRequest, NextResponse } from "next/server";
import { db, userNotificationPrefs, eq } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getNotificationPrefs } from "@/lib/notification-prefs";
import { z } from "zod";

const PutSchema = z.object({
  follow: z.boolean().optional(),
  comment: z.boolean().optional(),
  reply: z.boolean().optional(),
  reaction: z.boolean().optional(),
  rating: z.boolean().optional(),
  mention: z.boolean().optional(),
  leftoverExpiring: z.boolean().optional(),
  shoppingList: z.boolean().optional(),
  followEmail: z.boolean().optional(),
  commentEmail: z.boolean().optional(),
  replyEmail: z.boolean().optional(),
  reactionEmail: z.boolean().optional(),
  ratingEmail: z.boolean().optional(),
  mentionEmail: z.boolean().optional(),
  leftoverExpiringEmail: z.boolean().optional(),
  shoppingListEmail: z.boolean().optional(),
  weeklyDigestEmail: z.boolean().optional(),
});

export async function GET() {
  const { session, response } = await requireSession();
  if (response) return response;

  const prefs = await getNotificationPrefs(session!.user.id);
  return NextResponse.json({ data: prefs });
}

export async function PUT(req: NextRequest) {
  const { session, response } = await requireSession();
  if (response) return response;

  const parsed = PutSchema.safeParse(await req.json());
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  }

  const body = parsed.data;
  const userId = session!.user.id;

  await db
    .insert(userNotificationPrefs)
    .values({ id: crypto.randomUUID(), userId, ...body, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: userNotificationPrefs.userId,
      set: { ...body, updatedAt: new Date() },
    });

  return NextResponse.json({ ok: true });
}
