// GSDS Settlement Service
// Settlement execution with auto-close logic

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';
import { createHash } from 'crypto';
import { gsdsContractService } from './gsds-contract.service';


export interface SettlementRequest {
  derivativeId: string;
  settlementAmount: string;
  currencyCode: string;
  assetType: string; // fiat, cbdc, commodity, security, ssu
}

export interface SettlementResult {
  settlementId: string;
  status: string;
}

export class GsdsSettlementService {
  /**
   * Execute settlement
   */
  async executeSettlement(request: SettlementRequest): Promise<SettlementResult> {
    const derivative = await prisma.synthetic_derivatives.findUnique({
      where: { derivativeId: request.derivativeId },
    });

    if (!derivative) {
      throw new Error(`Derivative not found: ${request.derivativeId}`);
    }

    if (derivative.status !== 'active') {
      throw new Error(`Derivative is not active: ${derivative.status}`);
    }

    // Verify contract is still valid (collateral and SRI check)
    await gsdsContractService.activateContract(request.derivativeId);

    // Re-check status after activation check
    const updatedDerivative = await prisma.synthetic_derivatives.findUnique({
      where: { derivativeId: request.derivativeId },
    });

    if (updatedDerivative?.status === 'auto_closed') {
      throw new Error('Contract was auto-closed due to insufficient collateral or SRI threshold');
    }

    const settlementId = `GSDS-SETTLE-${uuidv4()}`;

    // Create hash lock for finality
    const hashLock = createHash('sha3-256')
      .update(`${request.derivativeId}-${request.settlementAmount}-${Date.now()}`)
      .digest('hex');

    const settlement = await prisma.synthetic_derivative_settlements.create({
      data: {
        id: uuidv4(),
        settlementId,
        derivativeId: request.derivativeId,
        settlementAmount: new Decimal(request.settlementAmount),
        currencyCode: request.currencyCode,
        assetType: request.assetType,
        hashLock,
        status: 'pending',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    // In production, this would trigger actual settlement on sovereign and DBIS ledgers
    // For now, mark as committed
    await prisma.synthetic_derivative_settlements.update({
      where: { settlementId },
      data: {
        status: 'committed',
        committedAt: new Date(),
        sovereignLedgerHash: `SOV-${hashLock.substring(0, 16)}`,
        dbisLedgerHash: `DBIS-${hashLock.substring(0, 16)}`,
        dualLedgerCommit: true,
      },
    });

    return {
      settlementId: settlement.settlementId,
      status: 'committed',
    };
  }

  /**
   * Finalize settlement
   */
  async finalizeSettlement(settlementId: string): Promise<void> {
    await prisma.synthetic_derivative_settlements.update({
      where: { settlementId },
      data: {
        status: 'final',
        settledAt: new Date(),
        finalizedAt: new Date(),
      },
    });
  }

  /**
   * Get settlement
   */
  async getSettlement(settlementId: string) {
    return await prisma.synthetic_derivative_settlements.findUnique({
      where: { settlementId },
      include: {
        synthetic_derivatives: true,
      },
    });
  }

  /**
   * List settlements for derivative
   */
  async listSettlements(derivativeId: string) {
    return await prisma.synthetic_derivative_settlements.findMany({
      where: { derivativeId },
      orderBy: { createdAt: 'desc' },
    });
  }
}

export const gsdsSettlementService = new GsdsSettlementService();

