import type {
  ComplaintVerificationResult,
  FaydaCallbackData,
} from "../types/complaint.types";
import {
  FaydaOidcError,
  registerFaydaCitizenFromCode,
} from "./faydaOidcService";
import {
  fetchRegistrationByTin,
  mapEtradeRegistration,
  resolveEtradeLanguage,
  TinRegistrationNotFoundError,
} from "./etradeTinService";

/**
 * Authenticates or registers a citizen via FAYDA OIDC using a single flow.
 */
export async function verifyComplaintUser(
  callbackData: FaydaCallbackData,
  language = "en",
): Promise<ComplaintVerificationResult> {
  if (!callbackData.code?.trim()) {
    throw new Error("Missing authorization code from FAYDA");
  }

  const { registration } = await registerFaydaCitizenFromCode(
    callbackData.code,
    language,
  );

  return {
    verified: true,
    method: "fayda",
    verifiedAt: new Date().toISOString(),
    registration,
  };
}

/**
 * Verifies an organization via the eTrade TIN registration API.
 */
export async function verifyComplaintTin(
  tin: string,
  language: string,
): Promise<ComplaintVerificationResult> {
  const normalizedTin = tin.trim();
  if (!/^\d{10}$/.test(normalizedTin)) {
    throw new Error("INVALID_TIN");
  }

  const registration = await fetchRegistrationByTin(
    normalizedTin,
    resolveEtradeLanguage(language),
  );

  const organization = mapEtradeRegistration(registration, normalizedTin);

  if (!organization.organizationName && !organization.tin) {
    throw new TinRegistrationNotFoundError();
  }

  return {
    verified: true,
    method: "tin",
    organization,
    verifiedAt: new Date().toISOString(),
  };
}

export { TinRegistrationNotFoundError };
export { FaydaOidcError };
