import { NextRequest, NextResponse } from "next/server";
import { db, userFeaturePrefs } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { getFeaturePrefs } from "@/lib/feature-prefs";
import { z } from "zod";

const PutSchema = z.object({
  nutrition: z.boolean().optional(),
  pantry: z.boolean().optional(),
  mealPlan: z.boolean().optional(),
  shoppingLists: z.boolean().optional(),
  collections: z.boolean().optional(),
  messages: z.boolean().optional(),
  chatbots: z.boolean().optional(),
});

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

  const prefs = await getFeaturePrefs(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(userFeaturePrefs)
    .values({ id: crypto.randomUUID(), userId, ...body, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: userFeaturePrefs.userId,
      set: { ...body, updatedAt: new Date() },
    });

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