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

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

    const { searchParams } = new URL(request.url);
    const limit  = Math.min(parseInt(searchParams.get("limit")  ?? "20"), 100);
    const offset = parseInt(searchParams.get("offset") ?? "0");
    const search = searchParams.get("search") ?? "";
    const style  = searchParams.get("style")  ?? "";

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

    if (style && style !== "all") query = query.eq("style", style);
    if (search) {
      query = query.or(
        `source_title.ilike.%${search}%,source_platform.ilike.%${search}%`
      );
    }

    const { data, count, error } = await query;
    if (error) throw error;

    return NextResponse.json({ success: true, data: data ?? [], total: count ?? 0 });
  } catch (e) {
    console.error("[storyboard/history]", e);
    return NextResponse.json({ success: false, error: "Internal server error" }, { status: 500 });
  }
}

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

    const { searchParams } = new URL(request.url);
    const id = searchParams.get("id");
    if (!id) return NextResponse.json({ success: false, error: "ID diperlukan" }, { status: 400 });

    const { error } = await supabase
      .from("storyboard_history")
      .delete()
      .eq("id", id)
      .eq("user_id", user.id);

    if (error) throw error;
    return NextResponse.json({ success: true });
  } catch (e) {
    console.error("[storyboard/history DELETE]", e);
    return NextResponse.json({ success: false, error: "Internal server error" }, { status: 500 });
  }
}
