/**
 * Script-safe phone parser.
 *
 * The project's existing `src/lib/i18n/phone.ts` imports from
 * `libphonenumber-js`, which under Node 25 + tsx loader hits a
 * metadata-shape interop bug (`{ default }` wrapping the JSON). It
 * works fine in Next.js + vitest, but a `tsx scripts/...` invocation
 * blows up.
 *
 * This wrapper bypasses the bundled `index.cjs.js` and calls
 * `libphonenumber-js/core` directly with metadata loaded as raw JSON.
 * Same surface as the i18n helper; usable from both runtimes.
 *
 * Used by the dedup library's `normalizePhone`. The runtime UI still
 * imports `i18n/phone` directly - no reason to touch a working path.
 */

// eslint-disable-next-line @typescript-eslint/no-require-imports
const core: typeof import('libphonenumber-js/core') = require('libphonenumber-js/core');
// Load the JSON directly. The bundled `index.cjs.js` does the same
// thing but its `require('../metadata.min.json')` hits a Node 25 ESM
// interop bug that wraps the JSON in `{ default }`. Importing the
// JSON file by absolute path through the package root sidesteps it.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-explicit-any
const metadata: any = require('libphonenumber-js/metadata.min.json');

import type { CountryCode } from '@/lib/i18n/countries';

export interface ParsedPhone {
  e164: string | null;
  country: CountryCode | null;
  national: string | null;
  international: string | null;
  isValid: boolean;
}

const EMPTY: ParsedPhone = {
  e164: null,
  country: null,
  national: null,
  international: null,
  isValid: false,
};

export function parsePhoneScriptSafe(raw: string, defaultCountry?: CountryCode): ParsedPhone {
  const trimmed = raw.trim();
  if (!trimmed) return EMPTY;
  try {
    // The core entry expects its own `CountryCode` type from
    // libphonenumber-js. Our `CountryCode` type is the same set of ISO
    // alpha-2 codes (we re-derive from the same Intl source) so this
    // cast is structural-equivalent, not lossy.
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const parsed = core.parsePhoneNumberFromString(trimmed, defaultCountry as any, metadata);
    if (!parsed) return EMPTY;
    return {
      e164: parsed.number,
      country: (parsed.country ?? null) as CountryCode | null,
      national: parsed.formatNational(),
      international: parsed.formatInternational(),
      isValid: parsed.isValid(),
    };
  } catch {
    return EMPTY;
  }
}
