// CBDC Supply Control Service
// Issue/Burn with dual-signature, stress-adjusted caps

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


export interface SupplyControlRequest {
  sovereignBankId: string;
  operationType: string; // issue, burn
  amount: number;
  dualSignature1: string;
  dualSignature2: string;
  stressAdjustedCap?: number;
  committeeId?: string;
}

export class CbdcSupplyControlService {
  /**
   * Create supply control operation
   */
  async createSupplyControl(request: SupplyControlRequest) {
    return await prisma.cbdc_supply_controls.create({
      data: {
        id: uuidv4(),
        controlId: `SUPPLY-${uuidv4()}`,
        committeeId: request.committeeId,
        sovereignBankId: request.sovereignBankId,
        operationType: request.operationType,
        amount: new Decimal(request.amount),
        dualSignature1: request.dualSignature1,
        dualSignature2: request.dualSignature2,
        stressAdjustedCap: request.stressAdjustedCap ? new Decimal(request.stressAdjustedCap) : null,
        status: 'pending',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });
  }

  /**
   * Approve supply control
   */
  async approveSupplyControl(controlId: string) {
    return await prisma.cbdc_supply_controls.update({
      where: { controlId },
      data: {
        status: 'approved',
        approvedAt: new Date(),
      },
    });
  }

  /**
   * Execute supply control
   */
  async executeSupplyControl(controlId: string) {
    return await prisma.cbdc_supply_controls.update({
      where: { controlId },
      data: {
        status: 'executed',
        executedAt: new Date(),
      },
    });
  }

  /**
   * Get supply controls
   */
  async getSupplyControls(sovereignBankId?: string, status?: string) {
    const where: any = {};
    if (sovereignBankId) {
      where.sovereignBankId = sovereignBankId;
    }
    if (status) {
      where.status = status;
    }

    return await prisma.cbdc_supply_controls.findMany({
      where,
      orderBy: {
        createdAt: 'desc',
      },
    });
  }
}

export const cbdcSupplyControlService = new CbdcSupplyControlService();

