// DSDM Market Service
// Market participant management

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


export interface ParticipantValidationRequest {
  participantBankId: string;
  participantType: string; // scb, supranational, pension_fund, licensed_institution
}

export interface DebtInstrumentRequest {
  issuerBankId: string;
  participantBankId: string;
  instrumentType: string; // bond, note, bill
  amount: string;
  currencyCode: string;
  maturityDate: Date;
}

export class DsdmMarketService {
  /**
   * Validate market participant
   */
  async validateParticipant(
    request: ParticipantValidationRequest
  ): Promise<boolean> {
    const { participantBankId, participantType } = request;

    // Check if participant type is valid
    const validTypes = ['scb', 'supranational', 'pension_fund', 'licensed_institution'];
    if (!validTypes.includes(participantType)) {
      return false;
    }

    // For SCB, check if it's a registered sovereign bank
    if (participantType === 'scb') {
      const bank = await prisma.sovereign_banks.findUnique({
        where: { id: participantBankId },
      });
      return bank !== null && bank.status === 'active';
    }

    // For other types, check if entity exists and is approved
    // In production, would have separate participant registry
    return true;
  }

  /**
   * Create sovereign debt instrument
   */
  async createDebtInstrument(
    request: DebtInstrumentRequest
  ): Promise<{ instrumentId: string }> {
    // Validate participant
    const isValid = await this.validateParticipant({
      participantBankId: request.participantBankId,
      participantType: 'scb', // Assume SCB for now
    });

    if (!isValid) {
      throw new Error('Invalid participant');
    }

    const instrumentId = `DEBT-${uuidv4()}`;

    const instrument = await prisma.sovereign_debt_instruments.create({
      data: {
        instrumentId,
        issuerBankId: request.issuerBankId,
        participantBankId: request.participantBankId,
        instrumentType: request.instrumentType,
        amount: new Decimal(request.amount),
        currencyCode: request.currencyCode,
        maturityDate: request.maturityDate,
        participantType: 'scb',
        status: 'active',
      },
    });

    return {
      instrumentId: instrument.instrumentId,
    };
  }

  /**
   * Get debt instruments for issuer
   */
  async getIssuerDebtInstruments(issuerBankId: string): Promise<any[]> {
    const instruments = await prisma.sovereign_debt_instruments.findMany({
      where: {
        issuerBankId,
        status: 'active',
      },
      orderBy: { maturityDate: 'asc' },
    });

    return instruments;
  }

  /**
   * Get debt instruments for participant
   */
  async getParticipantDebtInstruments(participantBankId: string): Promise<any[]> {
    const instruments = await prisma.sovereign_debt_instruments.findMany({
      where: {
        participantBankId,
        status: 'active',
      },
      orderBy: { maturityDate: 'asc' },
    });

    return instruments;
  }
}

export const dsdmMarketService = new DsdmMarketService();

