import { NextResponse } from "next/server";
import { createSbServer } from "@/lib/supabaseServer";

export async function GET(req: Request, ctx: { params: { id: string } }) {
  const { id } = ctx.params;
  try {
    const sb = createSbServer();

    // Try to get organization id from header if present
    const activeOrg = req.headers.get("x-active-org-id") || undefined;

    // Query Supabase notes table
    let q = sb.from("notes").select("*");
    q = q.eq("contract_id", id);
    if (activeOrg) q = q.eq("organization_id", activeOrg);

  // Order by source_created_at (newest first). If absent, fall back to created_at desc.
  q = q.order("source_created_at", { ascending: false, nullsFirst: false });
  q = q.order("created_at", { ascending: false });

    // Execute query and handle case where 'idx' column doesn't exist in the table
    let data: any = null;
    try {
      const res = await q;
      data = res.data;
      if (res.error) {
        // If error mentions missing 'source_created_at' column, retry ordering by created_at
        const msg = res.error.message ? String(res.error.message) : "";
        if (msg.includes("source_created_at") && msg.includes("does not exist") || msg.includes("column \"source_created_at\"")) {
          const q2 = sb.from("notes").select("*").eq("contract_id", id);
          if (activeOrg) q2.eq("organization_id", activeOrg);
          const res2 = await q2.order("created_at", { ascending: false });
          if (res2.error) {
            return NextResponse.json({ error: "supabase_error", message: res2.error.message }, { status: 502 });
          }
          data = res2.data;
        } else {
          return NextResponse.json({ error: "supabase_error", message: res.error.message }, { status: 502 });
        }
      }
    } catch (err: any) {
      // Some clients throw; handle missing column fallback as well
      const msg = err?.message ? String(err.message) : String(err);
      if ((msg.includes("source_created_at") && msg.includes("does not exist")) || msg.includes("column \"source_created_at\" does not exist") || msg.includes("column \"source_created_at\"")) {
        const q2 = sb.from("notes").select("*").eq("contract_id", id);
        if (activeOrg) q2.eq("organization_id", activeOrg);
        const res2 = await q2.order("created_at", { ascending: false });
        if (res2.error) {
          return NextResponse.json({ error: "supabase_error", message: res2.error.message }, { status: 502 });
        }
        data = res2.data;
      } else {
        return NextResponse.json({ error: "supabase_error", message: msg }, { status: 502 });
      }
    }

    return NextResponse.json({ items: Array.isArray(data) ? data : [] }, { status: 200 });
  } catch (e: any) {
    return NextResponse.json({ error: "internal_error", message: e?.message || String(e) }, { status: 500 });
  }
}

export async function POST(req: Request, ctx: { params: { id: string } }) {
  const { id } = ctx.params;
  try {
    const body = await req.json().catch(() => ({}));
    const content: string = (body && body.content) || "";
    const source: string = (body && body.source) || "Espace Paie";

    if (!content || !content.trim()) {
      return NextResponse.json({ error: "invalid_input", message: "content required" }, { status: 400 });
    }

    const sb = createSbServer();

    // Récupérer l'organization_id à partir du contrat (comme dans l'API payslips)
    const { data: contract, error: contractError } = await sb
      .from("cddu_contracts")
      .select("org_id")
      .eq("id", id)
      .single();

    if (contractError || !contract) {
      return NextResponse.json({ error: "contract_not_found", message: "Contrat non trouvé" }, { status: 404 });
    }

    const author = req.headers.get("x-company-name") || undefined;

    const insertPayload: any = {
      contract_id: id,
      content: content.trim(),
      source,
      organization_id: contract.org_id, // Utiliser l'org_id du contrat
    };
    if (author) insertPayload.author = author;

    const { data, error } = await sb.from("notes").insert([insertPayload]).select();
    if (error) {
      return NextResponse.json({ error: "supabase_error", message: error.message }, { status: 502 });
    }

    return NextResponse.json({ items: Array.isArray(data) ? data : [] }, { status: 201 });
  } catch (e: any) {
    return NextResponse.json({ error: "internal_error", message: e?.message || String(e) }, { status: 500 });
  }
}