import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase/server";
import { parseClientsCsv } from "@/lib/csv";

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

    const formData = await request.formData();
    const file = formData.get("file") as File | null;
    if (!file) {
      return NextResponse.json({ error: "Nie wybrano pliku." }, { status: 400 });
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    // Próba kilku popularnych kodowań, tak jak w lokalnym MVP (Excel z
    // polskiego Windowsa często zapisuje CSV w cp1250, nie UTF-8).
    let text: string | null = null;
    for (const encoding of ["utf-8", "latin1"] as const) {
      try {
        text = new TextDecoder(encoding, { fatal: false }).decode(buffer);
        break;
      } catch {
        continue;
      }
    }
    if (text === null) {
      return NextResponse.json(
        { error: "Nie udało się odczytać pliku -- zapisz CSV w kodowaniu UTF-8 i spróbuj ponownie." },
        { status: 400 }
      );
    }

    const { clients, warnings } = parseClientsCsv(text);

    if (clients.length > 0) {
      const rows = clients.map((c) => ({ ...c, owner_id: user.id }));
      const { error: insertError } = await supabase.from("clients").insert(rows);
      if (insertError) {
        return NextResponse.json(
          { error: `Błąd zapisu klientów: ${insertError.message}` },
          { status: 500 }
        );
      }
    }

    return NextResponse.json({ imported: clients.length, warnings });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
