import type {
  ClaimStatus, CompanyRole, CompanyType, CompanyVerificationStatus,
} from '@/types/db'

/**
 * Company roles, statuses and permissions (Tasks 88–92; article §10–§12,
 * §23, §24, §27).
 *
 * Nash (2026-09-08): "Who has the power to manage the profile of the
 * company?" — the owner/admin does; an agent does not. Verification itself
 * is OPTIONAL: nothing here is used to gate trips, chat or the intake page.
 */

export const COMPANY_ROLES: CompanyRole[] = [
  'company_owner',
  'company_admin',
  'broker_manager',
  'broker_agent',
  'billing_admin',
  'viewer',
]

/** Display names; carrier companies read manager/agent (§12 applies to both). */
export function companyRoleLabel(role: CompanyRole, type: CompanyType = 'broker'): string {
  switch (role) {
    case 'company_owner':
      return 'Company Owner'
    case 'company_admin':
      return 'Company Admin'
    case 'broker_manager':
      return type === 'carrier' ? 'Manager' : 'Broker Manager'
    case 'broker_agent':
      return type === 'carrier' ? 'Agent' : 'Broker Agent'
    case 'billing_admin':
      return 'Billing Admin'
    case 'viewer':
      return 'Viewer / Read-only'
  }
}

/** Capability flags per role (§10 admin powers, §11 what an agent must not do). */
export interface CompanyCapabilities {
  manageProfile: boolean
  manageMembers: boolean
  manageBilling: boolean
  manageIntakePage: boolean
  seeAllCompanyTrips: boolean
  createTrips: boolean
}

export function companyCapabilities(role: CompanyRole | null | undefined): CompanyCapabilities {
  switch (role) {
    case 'company_owner':
    case 'company_admin':
      return {
        manageProfile: true,
        manageMembers: true,
        manageBilling: true,
        manageIntakePage: true,
        seeAllCompanyTrips: true,
        createTrips: true,
      }
    case 'broker_manager':
      return {
        manageProfile: false,
        manageMembers: true,
        manageBilling: false,
        manageIntakePage: false,
        seeAllCompanyTrips: true,
        createTrips: true,
      }
    case 'billing_admin':
      return {
        manageProfile: false,
        manageMembers: false,
        manageBilling: true,
        manageIntakePage: false,
        seeAllCompanyTrips: false,
        createTrips: true,
      }
    case 'broker_agent':
      return {
        manageProfile: false,
        manageMembers: false,
        manageBilling: false,
        manageIntakePage: false,
        seeAllCompanyTrips: false,
        createTrips: true,
      }
    case 'viewer':
      return {
        manageProfile: false,
        manageMembers: false,
        manageBilling: false,
        manageIntakePage: false,
        seeAllCompanyTrips: false,
        createTrips: false,
      }
    default:
      return {
        manageProfile: false,
        manageMembers: false,
        manageBilling: false,
        manageIntakePage: false,
        seeAllCompanyTrips: false,
        createTrips: false,
      }
  }
}

/** "Corporate editing power" (Nash) — owner or admin only. */
export function canManageCompany(role: CompanyRole | null | undefined): boolean {
  return role === 'company_owner' || role === 'company_admin'
}

/** Article §23 levels. */
export const VERIFICATION_LEVELS: Record<CompanyVerificationStatus, number> = {
  unverified: 0,
  public_data_matched: 1,
  corporate_contact_confirmed: 2,
  company_admin_approved: 3,
  manual_verified: 4,
}

export const VERIFICATION_LABELS: Record<CompanyVerificationStatus, string> = {
  unverified: 'Unverified',
  public_data_matched: 'Public data matched',
  corporate_contact_confirmed: 'Corporate contact confirmed',
  company_admin_approved: 'Company admin approved',
  manual_verified: 'Manually verified',
}

/** Article §27 phrases — the only wording used in the UI for these states. */
export const CLAIM_LABELS: Record<ClaimStatus, string> = {
  company_claimed: 'Company claimed',
  company_match_found: 'Company match found',
  company_verification_pending: 'More information requested',
  pending_corporate_approval: 'Company approval pending',
  approved: 'Approved company agent',
  rejected: 'Not approved',
  revoked: 'Access revoked',
  admin_review_required: 'Under review by HeavyHaul Agent',
}

/** MC numbers are digits; people type "MC 088374", "MC-088374" or "088374". */
export function normalizeMc(raw: string): string | null {
  const digits = raw.replace(/\D/g, '')
  if (digits.length < 5 || digits.length > 8) return null
  return digits
}

const FREE_MAIL = new Set([
  'gmail.com', 'yahoo.com', 'outlook.com', 'hotmail.com', 'aol.com', 'icloud.com',
  'live.com', 'msn.com', 'protonmail.com', 'proton.me', 'mail.com', 'ymail.com',
])

/** Article §19 trigger "user uses Gmail/Yahoo/Outlook" — not a corporate domain. */
export function isFreeMailDomain(email: string | null | undefined): boolean {
  const domain = email?.split('@')[1]?.toLowerCase()
  return !!domain && FREE_MAIL.has(domain)
}

export function emailDomain(email: string | null | undefined): string | null {
  const d = email?.split('@')[1]?.toLowerCase().trim()
  return d || null
}

/** `abcfreight.com` from `https://www.abcfreight.com/about` (§8 Method 1). */
export function websiteDomain(website: string | null | undefined): string | null {
  if (!website) return null
  const cleaned = website.trim().replace(/^https?:\/\//i, '').replace(/^www\./i, '')
  const host = cleaned.split('/')[0].toLowerCase()
  return host || null
}

/**
 * The demo corporate email shown while the FMCSA lookup is backend-later
 * (Nash: "you put an email — test, temp validation email at email whatever").
 * Reads as a demo on purpose; never a real mailbox.
 */
export function demoCorporateEmail(mc: string): string {
  return `verification-demo+mc${mc}@heavyhaulagent.test`
}
