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

const ALLOWED_PLATFORMS = ["seedance", "gemini_omni", "kling_motion", "higgsfield", "tiktok_ugc", "all"] as const;

const TemplateCreateSchema = z.object({
  platform:    z.enum(ALLOWED_PLATFORMS),
  name:        z.string().min(1, "Nama template wajib diisi").max(200),
  description: z.string().max(500).optional(),
  input_data:  z.record(z.unknown()),
  is_public:   z.boolean().optional().default(false),
  tags:        z.array(z.string().max(50)).max(10).optional(),
});

export async function GET(request: NextRequest) {
  const supabase = createClient();
  const { data: { user } } = await supabase.auth.getUser();

  const { searchParams } = new URL(request.url);
  const rawPlatform = searchParams.get("platform");

  // Whitelist platform — cegah filter injection ke PostgREST
  const platform = rawPlatform && (ALLOWED_PLATFORMS as readonly string[]).includes(rawPlatform)
    ? rawPlatform
    : null;

  let query = supabase
    .from("prompt_templates")
    .select("*")
    .order("use_count", { ascending: false });

  if (user) {
    // Pakai .or() hanya untuk kondisi user vs public — user_id sudah aman (UUID dari auth)
    query = query.or(`user_id.eq.${user.id},is_public.eq.true`);
  } else {
    query = query.eq("is_public", true);
  }

  if (platform && platform !== "all") {
    // Gunakan .in() bukan .or() dengan interpolasi string — aman dari injection
    query = query.in("platform", [platform, "all"]);
  }

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

  return NextResponse.json({ data });
}

export async function POST(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();

  // Validasi & whitelist field — jangan percaya client untuk is_official atau user_id
  const parsed = TemplateCreateSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: "Validasi gagal", details: parsed.error.errors },
      { status: 400 }
    );
  }

  const { platform, name, description, input_data, is_public, tags } = parsed.data;

  const { data, error } = await supabase
    .from("prompt_templates")
    .insert({
      user_id: user.id,
      platform,
      name,
      description:  description ?? null,
      input_data,
      is_public:    is_public ?? false,
      is_official:  false,   // hanya admin yang bisa set lewat DB langsung
      tags:         tags ?? null,
    })
    .select()
    .single();

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

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");
  if (!id) return NextResponse.json({ error: "Template ID wajib diisi" }, { status: 400 });

  // RLS memastikan user hanya bisa hapus milik sendiri
  // is_official check: jangan izinkan user hapus template official
  const { data: tmpl, error: fetchErr } = await supabase
    .from("prompt_templates")
    .select("id, user_id, is_official")
    .eq("id", id)
    .eq("user_id", user.id)
    .single();

  if (fetchErr || !tmpl) {
    return NextResponse.json({ error: "Template tidak ditemukan atau bukan milikmu" }, { status: 404 });
  }

  if (tmpl.is_official) {
    return NextResponse.json({ error: "Template official tidak bisa dihapus" }, { status: 403 });
  }

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

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

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; use_count_increment?: boolean };
  if (!body.id) return NextResponse.json({ error: "Template ID wajib diisi" }, { status: 400 });

  // Satu-satunya update yang diizinkan dari client: increment use_count
  if (body.use_count_increment) {
    await supabase.rpc("increment_template_use_count", { p_template_id: body.id });
    return NextResponse.json({ success: true });
  }

  return NextResponse.json({ error: "Tidak ada operasi yang valid" }, { status: 400 });
}
