import type { AdapterName } from './options.js';

export type CapabilityRoute =
  | 'account'
  | 'estimate'
  | 'exceptions'
  | 'exceptionsSync'
  | 'health'
  | 'job'
  | 'jobs'
  | 'licenseActivate'
  | 'licenseDeactivate'
  | 'licenseStatus'
  | 'licenseValidate'
  | 'login'
  | 'plans'
  | 'plugin'
  | 'site'
  | 'sites'
  | 'subscribe'
  | 'staffLedger'
  | 'translate'
  | 'translateBulk'
  | 'updates';

export interface RequestDescription {
  url: string;
  headers: Record<string, string>;
}

export interface BackendAdapter {
  readonly name: AdapterName;
  readonly baseUrl: string;
  request(route: CapabilityRoute, credential?: string, id?: string): RequestDescription;
  unwrap(body: unknown): Record<string, unknown>;
  errorCode(body: unknown): string | undefined;
}

const LEGACY_PATHS: Record<CapabilityRoute, string> = {
  account: '/v1/account/credits', estimate: '/v1/estimate', exceptions: '/v1/exceptions', exceptionsSync: '/v1/exceptions/sync', health: '/health',
  job: '/v1/jobs/{id}', jobs: '/v1/jobs', licenseActivate: '/v1/international/license/activate',
  licenseDeactivate: '/v1/international/license/deactivate', licenseStatus: '/v1/international/license/status',
  licenseValidate: '/v1/international/license/validate', plans: '/v1/onboarding/plans?plugin=international',
  login: '/v1/auth/login', plugin: '/v1/plugin/{id}', staffLedger: '/v1/staff/ledger',
  site: '/v1/sites/{id}', sites: '/v1/sites/register', subscribe: '/v1/subscriptions/checkout',
  translate: '/v1/translate', translateBulk: '/v1/translate/bulk', updates: '/v1/international/updates/check',
};

const PLATFORM_PATHS: Record<CapabilityRoute, string> = {
  account: '/api/account', estimate: '/api/estimate', exceptions: '/api/exceptions', exceptionsSync: '/api/exceptions/sync', health: '/health',
  job: '/api/jobs/{id}', jobs: '/api/jobs', licenseActivate: '/api/license/activate',
  licenseDeactivate: '/api/license/deactivate', licenseStatus: '/api/license/status',
  licenseValidate: '/api/license/validate', plans: '/api/plans?plugin=international', sites: '/api/sites',
  login: '/api/auth/login', plugin: '/api/plugin/{id}', staffLedger: '/api/staff/ledger',
  site: '/api/sites/{id}', subscribe: '/api/subscribe', translate: '/api/translate',
  translateBulk: '/api/translate/bulk', updates: '/api/updates/check',
};

function object(value: unknown): Record<string, unknown> {
  return value !== null && typeof value === 'object' ? value as Record<string, unknown> : {};
}

export function createAdapter(name: AdapterName, baseUrl: string): BackendAdapter {
  const paths = name === 'legacy' ? LEGACY_PATHS : PLATFORM_PATHS;
  return {
    name,
    baseUrl,
    request(route, credential, id) {
      const headers: Record<string, string> = { 'Content-Type': 'application/json' };
      if (credential && name === 'legacy') {
        headers['X-Plugin'] = 'international';
        headers.Authorization = `Bearer ${credential}`;
      }
      if (credential && name === 'platform') headers.Authorization = `Bearer ${credential}`;
      return { url: `${baseUrl}${paths[route].replace('{id}', encodeURIComponent(id ?? 'missing'))}`, headers };
    },
    unwrap(body) {
      const root = object(body);
      return object(root.data ?? root);
    },
    errorCode(body) {
      const root = object(body);
      return String(object(root.error).code ?? root.code ?? '') || undefined;
    },
  };
}
