import { NextResponse } from "next/server";
import { createClient as createSupabaseClient } from "@supabase/supabase-js";
import { logApiError } from "@/lib/api/security";
import { createRouteClient } from "@/lib/supabase/route";
import { NOTE_TEMPLATE_CATEGORIES } from "@/lib/notes/note-templates";

function getSupabaseAdmin() {
  return createSupabaseClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
  );
}

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

    const { data: templates } = await supabase
      .from("note_design_templates")
      .select("*")
      .eq("creator_id", user.id)
      .order("created_at", { ascending: false });

    const ids = (templates || []).map((t) => t.id as string);
    const counts: Record<string, number> = {};
    if (ids.length > 0) {
      const admin = getSupabaseAdmin();
      const { data: purchases } = await admin
        .from("note_design_purchases")
        .select("design_id")
        .in("design_id", ids);
      for (const purchase of purchases || []) {
        const key = purchase.design_id as string;
        counts[key] = (counts[key] || 0) + 1;
      }
    }

    const result = (templates || []).map((t) => ({ ...t, purchase_count: counts[t.id as string] || 0 }));
    return NextResponse.json({ templates: result });
  } catch (error) {
    logApiError("Note template GET (mine) error", error);
    return NextResponse.json({ error: "Could not load your templates" }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const body = await req.json();
    const noteId = typeof body.noteId === "string" ? body.noteId : null;
    const name = String(body.name || "").trim();
    const description = typeof body.description === "string" ? body.description.trim() : "";
    const categoryRaw = String(body.category || "custom");
    const category = NOTE_TEMPLATE_CATEGORIES.includes(categoryRaw as (typeof NOTE_TEMPLATE_CATEGORIES)[number])
      ? categoryRaw
      : "custom";
    const icon = typeof body.icon === "string" && body.icon.trim() ? body.icon.trim().slice(0, 8) : "📄";
    const priceEuros = Number(body.price_euros || 0);
    const price_cents = Number.isFinite(priceEuros) && priceEuros > 0 ? Math.round(priceEuros * 100) : 0;

    if (!noteId) return NextResponse.json({ error: "Pick a note to turn into a template" }, { status: 400 });
    if (!name) return NextResponse.json({ error: "Name is required" }, { status: 400 });

    // RLS scopes this to notes the current user can actually read.
    const { data: note } = await supabase
      .from("notes")
      .select("content, source_template_price_cents")
      .eq("id", noteId)
      .maybeSingle();
    if (!note) return NextResponse.json({ error: "Note not found" }, { status: 404 });
    if ((note.source_template_price_cents || 0) > 0) {
      return NextResponse.json(
        { error: "This note was created from a paid template and can't be turned into a template itself." },
        { status: 403 },
      );
    }

    const { data, error } = await supabase
      .from("note_design_templates")
      .insert({
        creator_id: user.id,
        name,
        description,
        category,
        icon,
        price_cents,
        content: note.content,
        is_published: true,
      })
      .select()
      .single();
    if (error) throw error;

    return NextResponse.json({ template: data }, { status: 201 });
  } catch (error) {
    logApiError("Note template POST error", error);
    return NextResponse.json({ error: "Template could not be created" }, { status: 500 });
  }
}

export async function PATCH(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const body = await req.json();
    const id = typeof body.id === "string" ? body.id : null;
    if (!id) return NextResponse.json({ error: "Template id is required" }, { status: 400 });

    const { data: existing } = await supabase
      .from("note_design_templates")
      .select("id")
      .eq("id", id)
      .eq("creator_id", user.id)
      .maybeSingle();
    if (!existing) return NextResponse.json({ error: "Template not found" }, { status: 404 });

    const updates: Record<string, unknown> = {};
    if (body.price_euros !== undefined) {
      const priceEuros = Number(body.price_euros);
      updates.price_cents = Number.isFinite(priceEuros) && priceEuros > 0 ? Math.round(priceEuros * 100) : 0;
    }
    if (typeof body.is_published === "boolean") {
      updates.is_published = body.is_published;
    }

    const { data, error } = await supabase
      .from("note_design_templates")
      .update(updates)
      .eq("id", id)
      .select()
      .single();
    if (error) throw error;

    return NextResponse.json({ template: data });
  } catch (error) {
    logApiError("Note template PATCH error", error);
    return NextResponse.json({ error: "Template could not be updated" }, { status: 500 });
  }
}

export async function DELETE(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const body = await req.json();
    const id = typeof body.id === "string" ? body.id : null;
    if (!id) return NextResponse.json({ error: "Template id is required" }, { status: 400 });

    const { data: existing } = await supabase
      .from("note_design_templates")
      .select("id")
      .eq("id", id)
      .eq("creator_id", user.id)
      .maybeSingle();
    if (!existing) return NextResponse.json({ error: "Template not found" }, { status: 404 });

    await supabase.from("note_design_templates").delete().eq("id", id);
    return NextResponse.json({ success: true });
  } catch (error) {
    logApiError("Note template DELETE error", error);
    return NextResponse.json({ error: "Template could not be deleted" }, { status: 500 });
  }
}
