import { NextResponse } from "next/server";
import { canReadSupplierLookup, getCompanyContext } from "@/lib/company-context";
import { createAdminClient, createClient } from "@/lib/supabase-server";

async function getAuth() {
  const supabase = await createClient();
  const {
    data: { user },
    error,
  } = await supabase.auth.getUser();

  if (error || !user) {
    return { ok: false as const, status: 401, user: null, ctx: null };
  }

  const ctx = await getCompanyContext(supabase, user);
  /* Pedia `financial.read` enquanto o resto do modulo pede `suppliers.read`.
     Quem tivesse a chave nova concedida e a antiga negada abria a tela e levava
     403 justamente na aba que abre primeiro, sem ver mensagem nenhuma. */
  /* Consulta de apoio: quem lê qualquer tela de Fornecedores vê esta
     lista. Cobrar a chave do módulo deixava o painel de fornecedores sem
     a vitrine dele. */
  if (!canReadSupplierLookup(ctx, user.id)) {
    return { ok: false as const, status: 403, user, ctx: null };
  }

  return { ok: true as const, status: 200, user, ctx };
}

export async function GET() {
  const auth = await getAuth();
  if (!auth.ok || !auth.user || !auth.ctx) {
    return NextResponse.json({ error: auth.status === 401 ? "Não autenticado." : "Sem permissão." }, { status: auth.status });
  }

  const admin = createAdminClient();
  const companyId = auth.ctx.companyId;

  const [
    { data, error },
    { data: profile },
    { data: ownerMembership }
  ] = await Promise.all([
    admin
      .from("sponsored_suppliers")
      .select("id,name,legal_name,cnpj,category,city,email,phone,payment_terms_primary,payment_terms_secondary,subscriber_discount,image_url,description,website_url,notes,active,position,created_at,updated_at")
      .eq("active", true)
      .order("position", { ascending: true })
      .order("created_at", { ascending: false }),
    admin.from("profiles").select("address_city").eq("id", auth.user.id).maybeSingle(),
    admin.from("company_users").select("user_id,active").eq("company_id", companyId).eq("role", "owner").maybeSingle()
  ]);

  if (error) {
    if (error.code === "42P01") {
      return NextResponse.json({ ok: true, suppliers: [] });
    }
    return NextResponse.json({ error: "Não foi possível carregar os fornecedores patrocinados." }, { status: 400 });
  }

  const ownerProfileId =
    auth.ctx.ownerId ||
    (ownerMembership &&
    (ownerMembership as { active?: unknown; user_id?: unknown }).active !== false &&
    typeof (ownerMembership as { user_id?: unknown }).user_id === "string"
      ? String((ownerMembership as { user_id?: unknown }).user_id)
      : null);

  let ownerProfileCity: string | null = null;
  if (ownerProfileId && ownerProfileId !== auth.user.id) {
    const { data: ownerProfile } = await admin.from("profiles").select("address_city").eq("id", ownerProfileId).maybeSingle();
    if (ownerProfile && typeof ownerProfile.address_city === "string" && ownerProfile.address_city.trim()) {
      ownerProfileCity = ownerProfile.address_city;
    }
  }

  const companyCity = 
    typeof profile?.address_city === "string" && profile.address_city.trim()
      ? profile.address_city
      : ownerProfileCity
        ? ownerProfileCity
        : null;

  return NextResponse.json({ 
    ok: true, 
    suppliers: data || [],
    meta: { companyCity }
  });
}
