// GSDS Collateral Service
// Multi-asset collateral management

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


export interface AddCollateralRequest {
  derivativeId: string;
  assetType: string; // cbdc, ssu, commodity, security, fiat
  assetId?: string;
  amount: string;
  valuation: string;
  marginRequirement?: string;
}

export interface CollateralResult {
  collateralId: string;
  status: string;
}

export class GsdsCollateralService {
  /**
   * Add collateral to derivative
   */
  async addCollateral(request: AddCollateralRequest): Promise<CollateralResult> {
    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}`);
    }

    const collateralId = `GSDS-COLL-${uuidv4()}`;
    const marginRequirement = request.marginRequirement
      ? new Decimal(request.marginRequirement)
      : new Decimal(0);

    const collateral = await prisma.synthetic_derivative_collaterals.create({
      data: {
        id: uuidv4(),
        collateralId,
        derivativeId: request.derivativeId,
        assetType: request.assetType,
        assetId: request.assetId || null,
        amount: new Decimal(request.amount),
        valuation: new Decimal(request.valuation),
        marginRequirement,
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return {
      collateralId: collateral.collateralId,
      status: collateral.status,
    };
  }

  /**
   * Release collateral
   */
  async releaseCollateral(collateralId: string): Promise<void> {
    await prisma.synthetic_derivative_collaterals.update({
      where: { collateralId },
      data: {
        status: 'released',
        releasedAt: new Date(),
      },
    });
  }

  /**
   * Get collateral for derivative
   */
  async getCollateral(derivativeId: string) {
    return await prisma.synthetic_derivative_collaterals.findMany({
      where: {
        derivativeId,
        status: 'active',
      },
    });
  }

  /**
   * Calculate total collateral value
   */
  async calculateTotalCollateral(derivativeId: string): Promise<string> {
    const collaterals = await this.getCollateral(derivativeId);
    const total = collaterals.reduce(
      (sum, col) => sum.plus(col.valuation),
      new Decimal(0)
    );
    return total.toString();
  }
}

export const gsdsCollateralService = new GsdsCollateralService();

