/**
 * Résultat public d'une vérification, tel que le renvoie `public.verifier_attestation(code)`
 * (migration 20261126000004_verifacte.sql).
 */
import { estCivilite, type PersonneCitee } from '@notariat-ci/annuaire';
import { estCode } from './code.ts';

export interface Attestation {
  code: string;
  empreinte: string;
  /** Date ISO de l'acte. */
  dateActe: string;
  /** Version de l'algorithme du sceau (ADR 0006). */
  versionSceau: number;
  /** Horodatage ISO de l'enregistrement. */
  enregistreLe: string;
  /** Horodatage ISO de la révocation, ou `null`. */
  revoqueeLe: string | null;
  notaire: PersonneCitee;
}

export class AttestationInvalide extends Error {
  constructor(champ: string) {
    super(`Réponse de vérification invalide : champ « ${champ} »`);
    this.name = 'AttestationInvalide';
  }
}

type Ligne = Record<string, unknown>;

function texte(l: Ligne, champ: string, motif?: RegExp): string {
  const v = l[champ];
  if (typeof v !== 'string' || v === '' || (motif && !motif.test(v))) {
    throw new AttestationInvalide(champ);
  }
  return v;
}

export function lireAttestation(valeur: unknown): Attestation {
  if (typeof valeur !== 'object' || valeur === null) throw new AttestationInvalide('ligne');
  const l = valeur as Ligne;
  const code = texte(l, 'code');
  if (!estCode(code)) throw new AttestationInvalide('code');
  const civilite = l.notaire_civilite;
  if (!estCivilite(civilite)) throw new AttestationInvalide('notaire_civilite');
  const version = l.version_sceau;
  if (typeof version !== 'number' || !Number.isInteger(version) || version < 1) {
    throw new AttestationInvalide('version_sceau');
  }
  const revoquee = l.revoquee_le;
  if (revoquee !== null && revoquee !== undefined && typeof revoquee !== 'string') {
    throw new AttestationInvalide('revoquee_le');
  }
  return {
    code,
    empreinte: texte(l, 'empreinte', /^[0-9a-f]{64}$/),
    dateActe: texte(l, 'date_acte', /^\d{4}-\d{2}-\d{2}$/),
    versionSceau: version,
    enregistreLe: texte(l, 'enregistre_le'),
    revoqueeLe: revoquee ?? null,
    notaire: {
      slug: texte(l, 'notaire_slug'),
      civilite,
      nom: texte(l, 'notaire_nom'),
      prenoms: texte(l, 'notaire_prenoms'),
    },
  };
}

export interface ConfigurationApi {
  url: string;
  cle: string;
}

/**
 * Vérifie un code auprès de l'API publique. `null` : aucun acte sous ce code.
 * @throws Error si le réseau ou l'API échouent (à distinguer d'un code inconnu).
 */
export async function verifierCode(
  config: ConfigurationApi,
  code: string,
  options: { signal?: AbortSignal; fetch?: typeof fetch } = {},
): Promise<Attestation | null> {
  const reponse = await (options.fetch ?? fetch)(
    new URL('/rest/v1/rpc/verifier_attestation', config.url),
    {
      method: 'POST',
      headers: {
        apikey: config.cle,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({ code }),
      signal: options.signal,
    },
  );
  if (!reponse.ok) throw new Error(`Vérification impossible (HTTP ${reponse.status})`);
  const corps: unknown = await reponse.json();
  if (!Array.isArray(corps)) throw new AttestationInvalide('réponse');
  const [premiere] = corps as unknown[];
  return premiere === undefined ? null : lireAttestation(premiere);
}

/** Point de contrôle public du registre (Q-019) : sa taille et l'empreinte de sa dernière ligne. */
export interface TeteRegistre {
  lignes: number;
  hashLigne: string;
  /** Horodatage ISO de la dernière ligne. */
  enregistreLe: string;
}

/** Tête du registre, ou `null` si le registre est vide. */
export async function chargerTeteRegistre(
  config: ConfigurationApi,
  options: { fetch?: typeof fetch } = {},
): Promise<TeteRegistre | null> {
  const reponse = await (options.fetch ?? fetch)(
    new URL('/rest/v1/rpc/tete_registre', config.url),
    {
      method: 'POST',
      headers: {
        apikey: config.cle,
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: '{}',
    },
  );
  if (!reponse.ok) throw new Error(`Lecture du registre impossible (HTTP ${reponse.status})`);
  const corps: unknown = await reponse.json();
  const [ligne] = Array.isArray(corps) ? (corps as unknown[]) : [];
  if (ligne === undefined) return null;
  const l = ligne as Record<string, unknown>;
  if (
    typeof l.lignes !== 'number' ||
    typeof l.hash_ligne !== 'string' ||
    !/^[0-9a-f]{64}$/.test(l.hash_ligne) ||
    typeof l.enregistre_le !== 'string'
  ) {
    throw new AttestationInvalide('tête du registre');
  }
  return { lignes: l.lignes, hashLigne: l.hash_ligne, enregistreLe: l.enregistre_le };
}
