// UCP 600 - Documentary Credits

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


export class Ucp600Service {
  /**
   * Issue digital letter of credit
   */
  async issueLetterOfCredit(
    applicantBankId: string,
    beneficiaryBankId: string,
    amount: string,
    currencyCode: string,
    expiryDate: Date,
    documents?: Record<string, unknown>
  ): Promise<LetterOfCredit> {
    const lcId = `LC-${uuidv4()}`;

    const lc = await prisma.letters_of_credit.create({
      data: {
        id: uuidv4(),
        lcId,
        applicantBankId,
        beneficiaryBankId,
        amount: new Decimal(amount),
        currencyCode,
        expiryDate,
        status: LetterOfCreditStatus.ISSUED,
        documents: documents ? JSON.parse(JSON.stringify(documents)) : null,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return {
      id: lc.id,
      lcId: lc.lcId,
      applicantBankId: lc.applicantBankId,
      beneficiaryBankId: lc.beneficiaryBankId,
      amount: lc.amount.toString(),
      currencyCode: lc.currencyCode,
      expiryDate: lc.expiryDate,
      status: lc.status as LetterOfCreditStatus,
      documents: lc.documents as Record<string, unknown> | undefined,
      contractReference: lc.contractReference || undefined,
    };
  }

  /**
   * Verify documents (eUCP 2.0)
   */
  async verifyDocuments(lcId: string, documents: Record<string, unknown>): Promise<boolean> {
    const lc = await prisma.letters_of_credit.findUnique({
      where: { lcId },
    });

    if (!lc || !lc.documents) {
      return false;
    }

    // In production, this would perform detailed document verification
    // For now, simplified check
    return JSON.stringify(lc.documents) === JSON.stringify(documents);
  }
}

export const ucp600Service = new Ucp600Service();

