import { NextRequest, NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { isCsrfSafe, csrfForbiddenPayload } from "@/lib/csrf";

export async function GET(request: NextRequest) {
  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(request.url);
  const type      = searchParams.get("type");  // "ugc" | undefined
  const platform  = searchParams.get("platform");
  const favorites = searchParams.get("favorites") === "true";
  const page      = Math.max(1, parseInt(searchParams.get("page")  ?? "1"));
  const limit     = Math.min(100, Math.max(1, parseInt(searchParams.get("limit") ?? "20")));
  const offset    = (page - 1) * limit;

  // ── UGC history: baca dari ugc_history (full output) ────────────────────
  if (type === "ugc") {
    const favFilter = searchParams.get("favorites") === "true";
    let ugcQuery = supabase
      .from("ugc_history")
      .select("*", { count: "exact" })
      .eq("user_id", user.id)
      .order("created_at", { ascending: false })
      .range(offset, offset + limit - 1);

    if (platform) ugcQuery = ugcQuery.eq("platform", platform);
    if (favFilter) ugcQuery = ugcQuery.eq("is_favorite", true);

    const { data, error, count } = await ugcQuery;
    if (error) return NextResponse.json({ error: error.message }, { status: 500 });
    return NextResponse.json({ data, count, page, limit });
  }

  // ── Default: prompt_history ───────────────────────────────────────────────
  let query = supabase
    .from("prompt_history")
    .select("*", { count: "exact" })
    .eq("user_id", user.id)
    .order("created_at", { ascending: false })
    .range(offset, offset + limit - 1);

  if (platform) query = query.eq("platform", platform);
  if (favorites) query = query.eq("is_favorite", true);

  const { data, error, count } = await query;
  if (error) return NextResponse.json({ error: error.message }, { status: 500 });

  return NextResponse.json({ data, count, page, limit });
}

export async function PATCH(request: NextRequest) {
  // Fix Issue B: CSRF check
  if (!isCsrfSafe(request)) return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await request.json() as {
    id?: string;
    type?: "ugc" | "prompt";
    is_favorite?: boolean;
    title?: string;
    tags?: string[] | null;
  };

  if (!body.id) return NextResponse.json({ error: "ID required" }, { status: 400 });

  // Hanya update field yang benar-benar dikirim — jangan set undefined ke DB
  const updates: Record<string, unknown> = {};
  if (body.is_favorite !== undefined) updates.is_favorite = body.is_favorite;
  if (body.title       !== undefined) updates.title       = body.title || null;
  if (body.tags        !== undefined) updates.tags        = body.tags ?? null;

  if (Object.keys(updates).length === 0) {
    return NextResponse.json({ error: "Tidak ada field yang diupdate" }, { status: 400 });
  }

  const table = body.type === "ugc" ? "ugc_history" : "prompt_history";
  const { data, error } = await supabase
    .from(table)
    .update(updates)
    .eq("id", body.id)
    .eq("user_id", user.id)
    .select()
    .single();

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ data });
}

export async function DELETE(request: NextRequest) {
  // Fix Issue B: CSRF check
  if (!isCsrfSafe(request)) return NextResponse.json(csrfForbiddenPayload(), { status: 403 });
  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(request.url);
  const id   = searchParams.get("id");
  const type = searchParams.get("type"); // "ugc" | null → prompt_history
  if (!id) return NextResponse.json({ error: "ID required" }, { status: 400 });

  const table = type === "ugc" ? "ugc_history" : "prompt_history";
  const { error } = await supabase
    .from(table)
    .delete()
    .eq("id", id)
    .eq("user_id", user.id);

  if (error) return NextResponse.json({ error: error.message }, { status: 500 });
  return NextResponse.json({ success: true });
}
