/**
 * Country adapter resolver — system-i18n.
 *
 * `loadCountryAdapter` is the single dispatch point for country adapters.
 * Add new countries here when the supported-country set grows beyond IL.
 *
 * `getTenantCountryAdapter` is the primary entry point for route handlers:
 * reads `tenants.country_code` and delegates to `loadCountryAdapter`.
 */
import { eq } from 'drizzle-orm'
import type { CountryAdapter } from '@zync/types'
import type { Db } from '../client'
import { tenants } from '../schema/tenants'
import { createIsraelAdapter } from '../adapters/israel'

export class UnsupportedCountryError extends Error {
  constructor(countryCode: string) {
    super(`Unsupported country_code: ${countryCode}`)
    this.name = 'UnsupportedCountryError'
  }
}

/**
 * Returns the CountryAdapter for `countryCode`.
 * Throws `UnsupportedCountryError` for any code not in the supported set.
 */
export async function loadCountryAdapter(db: Db, countryCode: string): Promise<CountryAdapter> {
  switch (countryCode) {
    case 'IL':
      return createIsraelAdapter(db)
    default:
      throw new UnsupportedCountryError(countryCode)
  }
}

/**
 * Reads the tenant's `country_code` from the DB and returns the matching adapter.
 * Falls back to 'IL' if the tenant row is not found (new tenant race condition).
 */
export async function getTenantCountryAdapter(db: Db, tenantId: string): Promise<CountryAdapter> {
  const [t] = await db
    .select({ cc: tenants.countryCode })
    .from(tenants)
    .where(eq(tenants.id, tenantId))
    .limit(1)
  return loadCountryAdapter(db, t?.cc ?? 'IL')
}
