// DBIS Core Banking System - Core Type Definitions

// ============================================================================
// Ledger Types
// ============================================================================

export enum LedgerEntryType {
  TYPE_A = 'TYPE_A', // Fiat transfers
  TYPE_B = 'TYPE_B', // CBDC issuance/redemption
  TYPE_C = 'TYPE_C', // FX spot/forward/swap settlement entries
  TYPE_D = 'TYPE_D', // Commodity asset movement
  TYPE_E = 'TYPE_E', // Security transfers
  TYPE_F = 'TYPE_F', // Long-form multi-entry transactions
  TYPE_G = 'TYPE_G', // Smart contract authorized ledger entries
}

export enum LedgerEntryStatus {
  PENDING = 'pending',
  POSTED = 'posted',
  SETTLED = 'settled',
  REVERSED = 'reversed',
}

export enum AssetType {
  FIAT = 'fiat',
  CBDC = 'cbdc',
  COMMODITY = 'commodity',
  SECURITY = 'security',
  DERIVATIVE = 'derivative',
}

export interface LedgerEntry {
  id: string;
  ledgerId: string;
  debitAccountId: string;
  creditAccountId: string;
  amount: string; // Decimal as string
  currencyCode: string; // ISO 4217
  fxRate?: string; // Decimal as string
  assetType: AssetType;
  transactionType: LedgerEntryType;
  referenceId: string;
  timestampUtc: Date;
  blockHash: string;
  previousHash?: string;
  auditFlag: boolean;
  amlRiskScore?: number;
  status: LedgerEntryStatus;
  metadata?: Record<string, unknown>;
}

export interface MultiEntryTransaction {
  referenceId: string;
  entries: Array<{
    debitAccountId: string;
    creditAccountId: string;
    amount: string;
    currencyCode: string;
    assetType: AssetType;
  }>;
  fxRates?: Record<string, string>;
  metadata?: Record<string, unknown>;
}

// ============================================================================
// Account Types
// ============================================================================

export enum AccountType {
  SOVEREIGN = 'sovereign',
  TREASURY = 'treasury',
  COMMERCIAL = 'commercial',
  CORRESPONDENT = 'correspondent',
  SETTLEMENT = 'settlement',
}

export interface BankAccount {
  id: string;
  accountNumber: string;
  sovereignBankId: string;
  accountType: AccountType;
  currencyCode: string;
  assetType: AssetType;
  balance: string;
  availableBalance: string;
  reservedBalance: string;
  reserveRequirement?: string;
  status: string;
}

// ============================================================================
// FX Types
// ============================================================================

export enum FxTradeType {
  SPOT = 'spot',
  FORWARD = 'forward',
  SWAP = 'swap',
  OPTION = 'option',
  CBDC_CROSS_CHAIN = 'cbdc_cross_chain',
}

export enum FxOrderType {
  MARKET = 'market',
  LIMIT = 'limit',
  STOP = 'stop',
  SOVEREIGN = 'sovereign',
}

export enum FxSettlementMode {
  RTGS = 'RTGS',
  T_PLUS_1 = 'T+1',
  ATOMIC = 'atomic',
}

export interface FxPair {
  id: string;
  baseCurrency: string;
  quoteCurrency: string;
  pairCode: string;
  pricingMethod: 'VWAP' | 'TWAP' | 'DBIS_SCI';
  status: string;
}

export interface FxTrade {
  id: string;
  tradeId: string;
  sovereignBankId: string;
  fxPairId: string;
  baseCurrency: string;
  quoteCurrency: string;
  tradeType: FxTradeType;
  quantity: string;
  price: string;
  orderType: FxOrderType;
  initiatorEntity: string;
  counterpartyEntity?: string;
  settlementMode: FxSettlementMode;
  status: string;
  timestampUtc: Date;
}

export interface FxOrder {
  pair: string; // e.g., "OMF/USD"
  amount: string;
  side: 'buy' | 'sell';
  orderType: FxOrderType;
  settlement: FxSettlementMode;
  limitPrice?: string;
  timeInForce?: string;
}

// ============================================================================
// CBDC Types
// ============================================================================

export enum CbdcWalletType {
  RETAIL = 'retail',
  WHOLESALE = 'wholesale',
  INSTITUTIONAL = 'institutional',
}

export enum CbdcOperationType {
  MINT = 'mint',
  BURN = 'burn',
  TRANSFER = 'transfer',
}

export interface CbdcWallet {
  id: string;
  walletId: string;
  sovereignBankId: string;
  walletType: CbdcWalletType;
  currencyCode: string;
  balance: string;
  status: string;
  tieredAccess?: Record<string, unknown>;
}

export interface CbdcIssuance {
  id: string;
  recordId: string;
  sovereignBankId: string;
  walletId?: string;
  amountMinted: string;
  amountBurned: string;
  netChange: string;
  operationType: CbdcOperationType;
  operatorIdentity: string;
  reserveBacking?: string;
  timestampUtc: Date;
}

export interface CbdcOfflineCapsule {
  capsuleId: string;
  senderWalletId: string;
  receiverWalletId: string;
  amount: string;
  timestamp: Date;
  expiryWindow: number; // seconds
  doubleSpendToken: string;
  signature: string;
}

// ============================================================================
// Payment Types
// ============================================================================

export enum PaymentPriority {
  RTGS = 'RTGS',
  DNS = 'DNS',
  URGENT = 'urgent',
  NORMAL = 'normal',
}

export interface PaymentRequest {
  debtorAccount: string;
  creditorAccount: string;
  amount: string;
  currency: string;
  assetType: AssetType;
  priority: PaymentPriority;
  reference: string;
  metadata?: Record<string, unknown>;
}

export interface PaymentStatus {
  paymentId: string;
  status: 'pending' | 'processing' | 'settled' | 'failed' | 'reversed';
  ledgerEntryIds?: string[];
  errorMessage?: string;
}

// ============================================================================
// ISO 20022 Message Types
// ============================================================================

export enum IsoMessageType {
  PACS_008 = 'PACS.008', // FI to FI Credit Transfer
  PACS_002 = 'PACS.002', // Payment Status Report
  PACS_009 = 'PACS.009', // Financial Institution Direct Debit
  CAMT_053 = 'CAMT.053', // Bank to Customer Statement
  CAMT_056 = 'CAMT.056', // Payment Cancellation Request
  PAIN_001 = 'PAIN.001', // Customer Credit Transfer Initiation
  FXMT_001 = 'FXMT.001', // FX Order Submission
  FXMT_003 = 'FXMT.003', // FX Trade Execution Report
  FXMT_004 = 'FXMT.004', // FX Settlement Confirmation
}

export interface DbisExtension {
  sovId?: string; // Sovereign ID
  maci?: string; // Multi-Asset Class Indicator
  cbdcMode?: boolean; // CBDC Settlement Mode Flag
  sovereignPriority?: string; // HIGH, MEDIUM, LOW
  liquidityTier?: number;
}

export interface IsoMessage {
  id: string;
  messageId: string;
  sovereignBankId: string;
  messageType: IsoMessageType;
  direction: 'inbound' | 'outbound';
  status: 'pending' | 'processed' | 'failed' | 'acknowledged';
  rawMessage: string;
  parsedData?: Record<string, unknown>;
  dbisExtensions?: DbisExtension;
  hsmSignature?: string;
  createdAt: Date;
}

// PACS.008 Structure
export interface Pacs008Message {
  messageId: string;
  creationDateTime: Date;
  numberOfTransactions: number;
  creditTransferTransactionInfo: {
    paymentId: {
      instructionId: string;
      endToEndId: string;
    };
    paymentType: {
      serviceLevel: {
        code: string;
      };
    };
    interbankSettlementAmount: {
      currency: string;
      amount: string;
    };
    interbankSettlementDate: Date;
    debtor: {
      financialInstitution: {
        bicfi: string;
      };
    };
    creditor: {
      financialInstitution: {
        bicfi: string;
      };
    };
    remittanceInformation: {
      unstructured: string;
    };
  };
  dbisExtensions?: DbisExtension;
}

// FXMT.001 Structure
export interface Fxmt001Message {
  tradeId: string;
  operationType: 'BUY' | 'SELL';
  currencyPair: {
    baseCurrency: string;
    quoteCurrency: string;
  };
  tradeAmount: string;
  orderType: string;
  settlementType: string;
  dbisExtensions?: DbisExtension;
}

// ============================================================================
// Compliance Types
// ============================================================================

export enum ComplianceRecordType {
  AML_CHECK = 'aml_check',
  SANCTIONS_SCREENING = 'sanctions_screening',
  PEP_CHECK = 'pep_check',
  RISK_SCORE = 'risk_score',
}

export enum ComplianceStatus {
  CLEAR = 'clear',
  FLAGGED = 'flagged',
  BLOCKED = 'blocked',
}

export interface ComplianceRecord {
  id: string;
  sovereignBankId: string;
  transactionId?: string;
  recordType: ComplianceRecordType;
  entityName?: string;
  entityType?: string;
  riskScore: number;
  status: ComplianceStatus;
  screeningResult?: Record<string, unknown>;
}

export interface SuspiciousActivityReport {
  id: string;
  reportId: string;
  transactionId?: string;
  reportType: 'SAR' | 'STR';
  severity: 'low' | 'medium' | 'high' | 'critical';
  description: string;
  status: 'pending' | 'submitted' | 'acknowledged';
}

// ============================================================================
// Smart Contract Types
// ============================================================================

export enum ContractTemplateType {
  FX_SWAP = 'FX_SWAP',
  LETTER_OF_CREDIT = 'LETTER_OF_CREDIT',
  SOVEREIGN_GUARANTEE = 'SOVEREIGN_GUARANTEE',
  CBDC_CONDITIONAL = 'CBDC_CONDITIONAL',
  COMMODITY_REDEMPTION = 'COMMODITY_REDEMPTION',
}

export enum ContractState {
  DRAFT = 'draft',
  ACTIVE = 'active',
  EXECUTED = 'executed',
  EXPIRED = 'expired',
  CANCELLED = 'cancelled',
}

export interface SmartContract {
  id: string;
  contractId: string;
  sovereignBankId: string;
  templateType: ContractTemplateType;
  contractState: ContractState;
  parameters: Record<string, unknown>;
  signatories: string[];
  signatures?: Record<string, string>;
  executionResult?: Record<string, unknown>;
}

// ============================================================================
// Sovereign Identity Types
// ============================================================================

export enum IdentityType {
  MASTER = 'Master',
  TREASURY = 'Treasury',
  CBDC = 'CBDC',
  SETTLEMENT = 'Settlement',
  API = 'API',
}

export interface SovereignIdentity {
  id: string;
  sovereignBankId: string;
  identityType: IdentityType;
  identityKey: string;
  hsmKeyId?: string;
  certificate?: string;
  status: string;
}

// ============================================================================
// Treasury & Liquidity Types
// ============================================================================

export interface LiquidityForecast {
  id: string;
  sovereignBankId: string;
  forecastDate: Date;
  forecastType: 'daily' | 'weekly' | 'monthly';
  lcr?: string; // Liquidity Coverage Ratio
  nsfr?: string; // Net Stable Funding Ratio
  hqla?: string; // High-Quality Liquid Assets
  forecastData: Record<string, unknown>;
}

export interface InterbankCreditLine {
  id: string;
  sovereignBankId: string;
  counterpartyBankId: string;
  creditLimit: string;
  usedAmount: string;
  availableAmount: string;
  currencyCode: string;
  status: string;
  expiryDate?: Date;
}

// ============================================================================
// ICC Trade Finance Types
// ============================================================================

export enum LetterOfCreditStatus {
  ISSUED = 'issued',
  PRESENTED = 'presented',
  ACCEPTED = 'accepted',
  REJECTED = 'rejected',
  EXPIRED = 'expired',
}

export interface LetterOfCredit {
  id: string;
  lcId: string;
  applicantBankId: string;
  beneficiaryBankId: string;
  amount: string;
  currencyCode: string;
  expiryDate: Date;
  status: LetterOfCreditStatus;
  documents?: Record<string, unknown>;
  contractReference?: string;
}

export enum GuaranteeType {
  DEMAND_GUARANTEE = 'demand_guarantee',
  BANK_GUARANTEE = 'bank_guarantee',
}

export interface SovereignGuarantee {
  id: string;
  guaranteeId: string;
  guarantorBankId: string;
  beneficiaryBankId: string;
  amount: string;
  currencyCode: string;
  guaranteeType: GuaranteeType;
  expiryDate: Date;
  status: string;
  contractReference?: string;
}

// ============================================================================
// API Request/Response Types
// ============================================================================

export interface ApiResponse<T = unknown> {
  success: boolean;
  data?: T;
  error?: {
    code: string;
    message: string;
    details?: Record<string, unknown>;
  };
  timestamp: Date;
}

export interface PaginatedResponse<T> {
  data: T[];
  pagination: {
    page: number;
    pageSize: number;
    total: number;
    totalPages: number;
  };
}

// ============================================================================
// Security Types
// ============================================================================

export interface SovereignIdentityToken {
  token: string;
  sovereignBankId: string;
  apiRole: string;
  expiration: Date;
  signature: string; // ECC-521 HSM signature
}

export interface RequestSignature {
  signature: string; // X-SOV-SIGNATURE
  timestamp: string; // X-SOV-TIMESTAMP
  nonce: string; // X-SOV-NONCE
}

export interface JwtPayload {
  sovereignBankId?: string;
  identityType: string;
  employeeId?: string;
  email?: string;
  name?: string;
  roleName?: string;
  permissions?: string[];
  sessionType?: 'portal' | 'service';
  portalSurface?: 'admin' | 'member' | 'core';
  apiRole?: string;
  iat?: number;
  exp?: number;
  [key: string]: unknown;
}

// ============================================================================
// Error Types
// ============================================================================

// ============================================================================
// Volume XII: Unified Multiverse Monetary Constitution, Temporal Currency Engines, Interplanetary FX, Infinite-State Reserves, and Omega-Layer Settlement Fabric
// ============================================================================

export interface TemporalCurrencyUnit {
  tcuId: string;
  tcuCode: string;
  tcuName: string;
  description: string;
  baseCurrency?: string;
  presentValue: string;
  primeTemporalBond: boolean;
  status: string;
}

export interface TemporalProjection {
  projectionId: string;
  tcuId: string;
  projectionType: 'forward_indexed' | 'retro_correction';
  timeDelta: string;
  projectedValue: string;
  economicData?: Record<string, unknown>;
  confidence?: string;
  projectedAt: Date;
}

export interface TemporalStabilityState {
  stateId: string;
  tcuId: string;
  presentValue: string;
  futureWeight: string;
  retroFactor: string;
  ssuAnchor?: string;
  calculatedValue: string;
  stabilityScore?: string;
  calculatedAt: Date;
}

export interface InterplanetaryFxPair {
  corridorId: string;
  corridorName: string;
  originPlanet: string;
  destinationPlanet: string;
  baseCurrency: string;
  quoteCurrency: string;
  lagAdjustment: string;
  gravityFactor: string;
  radiationRiskSpread: string;
  velocityNormalization: string;
}

export interface AifxTrade {
  tradeId: string;
  corridorId: string;
  sovereignBankId: string;
  baseCurrency: string;
  quoteCurrency: string;
  amount: string;
  fxPrice: string;
  liquidityWeight: string;
  gravityFactor: string;
  latencyCost: string;
  timeDilationIndex: string;
  ssuStability?: string;
  settlementMode: string;
  status: string;
}

export interface OmegaLayerState {
  stateId: string;
  layerId: string;
  layerNumber: number;
  layerName: string;
  stateHash: string;
  stateData: Record<string, unknown>;
  primeState?: Record<string, unknown>;
  quantumState?: Record<string, unknown>;
  holographicState?: Record<string, unknown>;
  parallelState?: Record<string, unknown>;
  temporalState?: Record<string, unknown>;
  mergedState?: Record<string, unknown>;
  consistencyStatus: string;
  timestamp: Date;
}

export interface MultiverseReserve {
  reserveId: string;
  reserveName: string;
  classicalReserve: string;
  quantumReserve?: string;
  parallelReserve?: string;
  holographicReserve?: string;
  temporalReserve?: string;
  totalReserve: string;
  variance?: string;
  entropy?: string;
  status: string;
}

export interface SovereignContinuityIdentity {
  continuityId: string;
  sovereignBankId: string;
  unifiedIdentity: string;
  classicalIdentity?: string;
  quantumIdentity?: string;
  holographicIdentity?: string;
  parallelIdentity?: Record<string, unknown>[];
  temporalIdentity?: string;
  status: string;
}

export interface UmmcConstitutionalPillar {
  pillarId: string;
  pillarNumber: number;
  pillarName: string;
  description: string;
  status: string;
}

export interface UmmcBindingClause {
  clauseId: string;
  clauseCode: string;
  clauseName: string;
  description: string;
  pillarId?: string;
  bindingType: string;
  enforcementLevel: string;
  status: string;
}

export enum ErrorCode {
  // Sovereign validation failures
  X100 = 'X100',
  // AML blocks
  X220 = 'X220',
  // Ledger hash mismatch
  X402 = 'X402',
  // FX liquidity unavailable
  X760 = 'X760',
  // Generic errors
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  NOT_FOUND = 'NOT_FOUND',
  UNAUTHORIZED = 'UNAUTHORIZED',
  FORBIDDEN = 'FORBIDDEN',
  INTERNAL_ERROR = 'INTERNAL_ERROR',
}

export class DbisError extends Error {
  constructor(
    public code: ErrorCode,
    message: string,
    public details?: Record<string, unknown>
  ) {
    super(message);
    this.name = 'DbisError';
  }
}
