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

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

  const rows = await db.query.aiConversations.findMany({
    where: eq(aiConversations.userId, session!.user.id),
    orderBy: desc(aiConversations.updatedAt),
  });

  return NextResponse.json({
    data: rows.map((r) => ({
      id: r.id,
      title: r.title,
      createdAt: r.createdAt.toISOString(),
      updatedAt: r.updatedAt.toISOString(),
    })),
  });
}

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

  const id = crypto.randomUUID();
  const now = new Date();
  await db.insert(aiConversations).values({ id, userId: session!.user.id, title: null, createdAt: now, updatedAt: now });

  return NextResponse.json({ id, title: null, createdAt: now.toISOString(), updatedAt: now.toISOString() }, { status: 201 });
}
