import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import { isMissingColumn } from '@/lib/db-compat'
import { demoCorporateEmail } from '@/lib/domain/company'
import type { Company } from '@/types/db'

/**
 * Company lookup by MC number (Task 89).
 *
 * Order: (1) our own `companies` table; (2) the FMCSA API — TODO(backend),
 * Nash (2026-09-08): "the FMCSA API integration is something that will be
 * done later, where we have access to validate partial information about the
 * company"; (3) until then, a clearly labelled DEMO company built from the
 * MC number so the request flow can be reviewed end to end ("for now, we
 * can just do a demo and show how that works").
 *
 * The result never pretends to be public-record data: `source` says where
 * it came from and the demo email reads as a demo.
 */
export type CompanyLookupResult =
  | { source: 'local'; company: Company }
  | { source: 'fmcsa'; company: Company } // reserved for the backend integration
  | {
      source: 'demo'
      company: null
      display_name: string
      corporate_email: string
    }

export async function lookupCompanyByMc(mc: string): Promise<CompanyLookupResult> {
  const admin = createAdminClient()
  const { data, error } = await admin
    .from('companies')
    .select('*')
    .eq('mc_number', mc)
    .is('merged_into', null)
    .maybeSingle()
  if (data) return { source: 'local', company: data as Company }
  if (error && !isMissingColumn(error, 'companies', 'mc_number')) {
    console.error('company lookup failed', error.message)
  }

  // TODO(backend): FMCSA lookup by MC → legal name, DBA, address, phone,
  // authority status and the corporate email on file. Returns partial data.

  return {
    source: 'demo',
    company: null,
    display_name: `Company on file for MC ${mc}`,
    corporate_email: demoCorporateEmail(mc),
  }
}
