import { NextRequest, NextResponse } from 'next/server'

// Proxy para BrasilAPI — evita CORS no client e centraliza o fallback
export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ cnpj: string }> },
) {
  const { cnpj } = await params
  const digits   = cnpj.replace(/\D/g, '')

  if (digits.length !== 14) {
    return NextResponse.json({ error: 'CNPJ deve ter 14 dígitos' }, { status: 400 })
  }

  // Tenta BrasilAPI primeiro, fallback para CNPJ.ws
  const sources = [
    `https://brasilapi.com.br/api/cnpj/v1/${digits}`,
    `https://publica.cnpj.ws/cnpj/${digits}`,
  ]

  let raw: Record<string, unknown> | null = null

  for (const url of sources) {
    try {
      const res = await fetch(url, {
        headers: { Accept: 'application/json', 'User-Agent': 'ravapi-crm/1.0' },
        signal: AbortSignal.timeout(8000),
      })
      if (res.ok) {
        raw = await res.json()
        break
      }
    } catch {
      // tenta próxima fonte
    }
  }

  if (!raw) {
    return NextResponse.json({ error: 'CNPJ não encontrado ou API indisponível' }, { status: 404 })
  }

  // Normaliza campos das duas fontes (BrasilAPI e CNPJ.ws têm nomes ligeiramente diferentes)
  const dddTelRaw = (raw.ddd_telefone_1 ?? raw.telefone ?? '') as string
  const dddTel    = dddTelRaw.replace(/\D/g, '')

  // CEP — remove hífen
  const cep = ((raw.cep ?? '') as string).replace(/\D/g, '')

  // CNAE fiscal — pode ser número ou string
  const cnae = raw.cnae_fiscal
    ? String(raw.cnae_fiscal).padStart(7, '0')
    : null

  // Situação cadastral descritiva
  const situacao = (
    raw.descricao_situacao_cadastral ??
    raw.situacao_cadastral ??
    null
  ) as string | null

  return NextResponse.json({
    cnpj:               digits,
    razao_social:       (raw.razao_social ?? '') as string,
    nome_fantasia:      ((raw.nome_fantasia ?? '') as string) || null,
    municipio:          ((raw.municipio ?? raw.municipio_descricao ?? '') as string).toUpperCase(),
    uf:                 ((raw.uf ?? '') as string).toUpperCase(),
    ddd1:               dddTel.slice(0, 2) || null,
    telefone1:          dddTel.slice(2)    || null,
    email:              ((raw.email ?? '') as string) || null,
    cnae_principal:     cnae,
    logradouro:         ((raw.logradouro ?? raw.tipo_logradouro_descricao ?? '') as string) || null,
    numero:             ((raw.numero ?? '') as string) || null,
    complemento:        ((raw.complemento ?? '') as string) || null,
    bairro:             ((raw.bairro ?? '') as string) || null,
    cep:                cep || null,
    natureza_juridica:  ((raw.natureza_juridica ?? raw.natureza_juridica_descricao ?? '') as string) || null,
    porte_empresa:      ((raw.porte ?? raw.porte_empresa ?? '') as string) || null,
    data_abertura:      ((raw.data_inicio_atividade ?? raw.abertura ?? '') as string) || null,
    situacao_cadastral: situacao,
    // Flag: ativo somente se situação = ATIVA
    ativa: typeof situacao === 'string'
      ? situacao.toUpperCase().includes('ATIVA') || situacao === '02'
      : true,
  })
}
