// URDG 758 - Demand Guarantees

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { SovereignGuarantee, GuaranteeType } from '@/shared/types';
import { v4 as uuidv4 } from 'uuid';


export class Urdg758Service {
  /**
   * Issue sovereign guarantee
   */
  async issueGuarantee(
    guarantorBankId: string,
    beneficiaryBankId: string,
    amount: string,
    currencyCode: string,
    guaranteeType: GuaranteeType,
    expiryDate: Date
  ): Promise<SovereignGuarantee> {
    const guaranteeId = `GUARANTEE-${uuidv4()}`;

    const guarantee = await prisma.sovereignGuarantee.create({
      data: {
        guaranteeId,
        guarantorBankId,
        beneficiaryBankId,
        amount: new Decimal(amount),
        currencyCode,
        guaranteeType,
        expiryDate,
        status: 'active',
      },
    });

    return {
      id: guarantee.id,
      guaranteeId: guarantee.guaranteeId,
      guarantorBankId: guarantee.guarantorBankId,
      beneficiaryBankId: guarantee.beneficiaryBankId,
      amount: guarantee.amount.toString(),
      currencyCode: guarantee.currencyCode,
      guaranteeType: guarantee.guaranteeType as GuaranteeType,
      expiryDate: guarantee.expiryDate,
      status: guarantee.status,
      contractReference: guarantee.contractReference || undefined,
    };
  }

  /**
   * Invoke guarantee
   */
  async invokeGuarantee(guaranteeId: string): Promise<void> {
    await prisma.sovereignGuarantee.update({
      where: { guaranteeId },
      data: { status: 'invoked' },
    });
  }
}

export const urdg758Service = new Urdg758Service();

