import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, aiConversations, eq, and } from "@epicure/db";
import { requireSessionOrApiKey } from "@/lib/api-auth";

type Params = { params: Promise<{ id: string }> };

const RenameSchema = z.object({ title: z.string().max(100).nullable() });

export async function PATCH(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { id } = await params;

  const body = await req.json() as unknown;
  const parsed = RenameSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: "Validation error" }, { status: 400 });
  }

  const [updated] = await db
    .update(aiConversations)
    .set({ title: parsed.data.title?.trim() || null, updatedAt: new Date() })
    .where(and(eq(aiConversations.id, id), eq(aiConversations.userId, session!.user.id)))
    .returning();

  if (!updated) return NextResponse.json({ error: "Not found" }, { status: 404 });

  return NextResponse.json({ id: updated.id, title: updated.title });
}

export async function DELETE(req: NextRequest, { params }: Params) {
  const { session, response } = await requireSessionOrApiKey(req);
  if (response) return response;
  const { id } = await params;

  const [deleted] = await db
    .delete(aiConversations)
    .where(and(eq(aiConversations.id, id), eq(aiConversations.userId, session!.user.id)))
    .returning({ id: aiConversations.id });

  if (!deleted) return NextResponse.json({ error: "Not found" }, { status: 404 });

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