// Alignment Contract (ACX) Service
// Smart contracts for re-alignment targets, FX corridor limits, SSU stabilization

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


export interface CreateAcxRequest {
  parityId: string;
  contractType: 're_alignment_target' | 'fx_corridor_limit' | 'ssu_stabilization';
  contractRules: Record<string, unknown>;
  targetValue?: number;
  threshold?: number;
}

export class AcxService {
  /**
   * Create alignment contract
   */
  async createContract(request: CreateAcxRequest) {
    const contractId = `ACX-${uuidv4()}`;

    const contract = await prisma.alignmentContract.create({
      data: {
        contractId,
        parityId: request.parityId,
        contractType: request.contractType,
        contractRules: request.contractRules,
        targetValue: request.targetValue ? new Decimal(request.targetValue) : null,
        threshold: request.threshold ? new Decimal(request.threshold) : null,
        status: 'active',
      },
    });

    return contract;
  }

  /**
   * Get contract by ID
   */
  async getContract(contractId: string) {
    const contract = await prisma.alignmentContract.findUnique({
      where: { contractId },
      include: {
        parity: true,
      },
    });

    if (!contract) {
      throw new Error(`Contract not found: ${contractId}`);
    }

    return contract;
  }

  /**
   * Get contracts for parity
   */
  async getContractsForParity(parityId: string) {
    return prisma.alignmentContract.findMany({
      where: {
        parityId,
        status: 'active',
      },
      include: {
        parity: true,
      },
    });
  }

  /**
   * Check and trigger contract
   */
  async checkContract(contractId: string, currentValue: number) {
    const contract = await prisma.alignmentContract.findUnique({
      where: { contractId },
      include: {
        parity: true,
      },
    });

    if (!contract) {
      throw new Error(`Contract not found: ${contractId}`);
    }

    if (contract.status !== 'active') {
      return { triggered: false, reason: 'Contract not active' };
    }

    let triggered = false;
    const current = new Decimal(currentValue);

    switch (contract.contractType) {
      case 're_alignment_target':
        if (contract.targetValue) {
          const deviation = current.minus(contract.targetValue).abs();
          if (contract.threshold && deviation.gte(contract.threshold)) {
            triggered = true;
          }
        }
        break;
      case 'fx_corridor_limit':
        if (contract.threshold) {
          if (current.gt(contract.threshold) || current.lt(contract.threshold.neg())) {
            triggered = true;
          }
        }
        break;
      case 'ssu_stabilization':
        if (contract.threshold) {
          const stabilityDeviation = current.minus(contract.targetValue || 0).abs();
          if (stabilityDeviation.gt(contract.threshold)) {
            triggered = true;
          }
        }
        break;
    }

    if (triggered) {
      await prisma.alignmentContract.update({
        where: { contractId },
        data: {
          status: 'triggered',
          triggeredAt: new Date(),
        },
      });
    }

    return {
      triggered,
      contract,
      currentValue: current.toNumber(),
    };
  }

  /**
   * Get all contracts
   */
  async getAllContracts(filters?: {
    parityId?: string;
    contractType?: string;
    status?: string;
  }) {
    const where: Record<string, unknown> = {};

    if (filters?.parityId) {
      where.parityId = filters.parityId;
    }
    if (filters?.contractType) {
      where.contractType = filters.contractType;
    }
    if (filters?.status) {
      where.status = filters.status;
    }

    return prisma.alignmentContract.findMany({
      where,
      include: {
        parity: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });
  }
}

export const acxService = new AcxService();

