import { NextRequest, NextResponse } from 'next/server';
import { getSupabaseAdmin } from '@/lib/supabase';

// GET: list distinct centres (deduped by name) sorted alphabetically.
// Used by the MatchingDetail dialog to populate the "Assigner à un
// centre existant" autocomplete.
export async function GET() {
  try {
    const supabase = getSupabaseAdmin();
    const { data, error } = await supabase
      .from('centre_codes')
      .select('name, is_suc')
      .order('name', { ascending: true });
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    // Dedupe by name; if any row marks the centre SUC, treat it as SUC.
    const map = new Map<string, { name: string; is_suc: boolean }>();
    for (const row of (data ?? []) as { name: string; is_suc: boolean }[]) {
      if (!row.name) continue;
      const existing = map.get(row.name);
      if (!existing) {
        map.set(row.name, { name: row.name, is_suc: !!row.is_suc });
      } else if (row.is_suc) {
        existing.is_suc = true;
      }
    }
    return NextResponse.json(Array.from(map.values()));
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Erreur inconnue';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

// POST: create a centre_codes row
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { supplier, code, name, is_suc } = body;
    if (!supplier || !code || !name) {
      return NextResponse.json(
        { error: 'supplier, code et name requis' },
        { status: 400 },
      );
    }
    const supabase = getSupabaseAdmin();
    const { data, error } = await supabase
      .from('centre_codes')
      .insert({
        supplier,
        code: String(code).trim(),
        name: String(name).trim(),
        is_suc: is_suc === true || is_suc === 'true',
      })
      .select()
      .single();
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 500 });
    }
    return NextResponse.json(data);
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Erreur inconnue';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
