// Settlement Dispute Service
// Dispute resolution workflow

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


export interface DisputeRequest {
  transactionId: string;
  party1BankId: string;
  party2BankId: string;
  disputeType: string; // settlement, finality, cross_border
  description: string;
  articleNumber?: string;
}

export interface DisputeStageResult {
  disputeId: string;
  stage: string;
  status: string;
}

export class SettlementDisputeService {
  /**
   * Create dispute
   */
  async createDispute(request: DisputeRequest): Promise<{ disputeId: string }> {
    // Get relevant article if specified
    let articleId: string | undefined;
    if (request.articleNumber) {
      const article = await prisma.settlementLawArticle.findFirst({
        where: {
          articleNumber: request.articleNumber,
          status: 'active',
        },
      });
      articleId = article?.articleId;
    }

    const disputeId = `DISPUTE-${uuidv4()}`;

    const dispute = await prisma.settlementDispute.create({
      data: {
        disputeId,
        transactionId: request.transactionId,
        articleId: articleId || null,
        party1BankId: request.party1BankId,
        party2BankId: request.party2BankId,
        disputeType: request.disputeType,
        description: request.description,
        stage: 'bilateral',
        status: 'active',
      },
    });

    return {
      disputeId: dispute.disputeId,
    };
  }

  /**
   * Escalate to CAA review
   */
  async escalateToCAA(disputeId: string): Promise<DisputeStageResult> {
    const dispute = await prisma.settlementDispute.findUnique({
      where: { disputeId },
    });

    if (!dispute) {
      throw new Error(`Dispute not found: ${disputeId}`);
    }

    if (dispute.stage !== 'bilateral') {
      throw new Error(`Dispute must be in bilateral stage: ${dispute.stage}`);
    }

    await prisma.settlementDispute.update({
      where: { disputeId },
      data: {
        stage: 'caa_review',
      },
    });

    return {
      disputeId: dispute.disputeId,
      stage: 'caa_review',
      status: dispute.status,
    };
  }

  /**
   * Escalate to Arbitration Tribunal
   */
  async escalateToArbitration(disputeId: string): Promise<DisputeStageResult> {
    const dispute = await prisma.settlementDispute.findUnique({
      where: { disputeId },
    });

    if (!dispute) {
      throw new Error(`Dispute not found: ${disputeId}`);
    }

    if (dispute.stage !== 'caa_review') {
      throw new Error(`Dispute must be in CAA review stage: ${dispute.stage}`);
    }

    await prisma.settlementDispute.update({
      where: { disputeId },
      data: {
        stage: 'arbitration_tribunal',
      },
    });

    return {
      disputeId: dispute.disputeId,
      stage: 'arbitration_tribunal',
      status: dispute.status,
    };
  }

  /**
   * Resolve dispute
   */
  async resolveDispute(
    disputeId: string,
    resolution: string
  ): Promise<void> {
    await prisma.settlementDispute.update({
      where: { disputeId },
      data: {
        status: 'resolved',
        resolution,
        resolvedAt: new Date(),
      },
    });
  }

  /**
   * Get dispute details
   */
  async getDispute(disputeId: string): Promise<any | null> {
    const dispute = await prisma.settlementDispute.findUnique({
      where: { disputeId },
      include: {
        article: true,
        arbitrations: true,
      },
    });

    return dispute;
  }

  /**
   * Get disputes by stage
   */
  async getDisputesByStage(stage: string): Promise<any[]> {
    const disputes = await prisma.settlementDispute.findMany({
      where: {
        stage,
        status: 'active',
      },
      orderBy: { createdAt: 'desc' },
    });

    return disputes;
  }
}

export const settlementDisputeService = new SettlementDisputeService();

