// Settlement Finality Service
// Finality enforcement (Principle 1)

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';


export interface FinalityRequest {
  transactionId: string;
  masterLedgerCommit: boolean;
}

export interface FinalityResult {
  finalityId: string;
  legalBinding: boolean;
  principle: string;
  status: string;
}

export class SettlementFinalityService {
  /**
   * Enforce settlement finality (Principle 1)
   */
  async enforceFinality(
    request: FinalityRequest
  ): Promise<FinalityResult> {
    // Get Principle 1 article
    const principle1Articles = await prisma.settlementLawArticle.findMany({
      where: {
        principle: 'Principle 1',
        status: 'active',
      },
    });

    if (principle1Articles.length === 0) {
      throw new Error('Principle 1 articles not found');
    }

    // Use first Principle 1 article
    const article = principle1Articles[0];

    // Create finality record
    const finalityId = `FINALITY-${uuidv4()}`;
    const finality = await prisma.settlementFinality.create({
      data: {
        finalityId,
        transactionId: request.transactionId,
        articleId: article.articleId,
        masterLedgerCommit: request.masterLedgerCommit,
        legalBinding: request.masterLedgerCommit, // Legal binding when master ledger commits
        principle: 'Principle 1',
        status: request.masterLedgerCommit ? 'final' : 'pending',
        finalizedAt: request.masterLedgerCommit ? new Date() : null,
      },
    });

    return {
      finalityId: finality.finalityId,
      legalBinding: finality.legalBinding,
      principle: finality.principle,
      status: finality.status,
    };
  }

  /**
   * Check if transaction is final
   */
  async isFinal(transactionId: string): Promise<boolean> {
    const finality = await prisma.settlementFinality.findFirst({
      where: {
        transactionId,
        status: 'final',
      },
    });

    return finality !== null;
  }

  /**
   * Get finality record
   */
  async getFinality(transactionId: string): Promise<any | null> {
    const finality = await prisma.settlementFinality.findFirst({
      where: { transactionId },
      include: { article: true },
      orderBy: { finalizedAt: 'desc' },
    });

    return finality;
  }
}

export const settlementFinalityService = new SettlementFinalityService();

