// DBIS Dispute Resolution Service
// Three-stage arbitration: bilateral → CAA mediation → binding arbitration

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


export interface DisputeData {
  sovereignBankId1: string;
  sovereignBankId2: string;
  disputeType: string;
  description: string;
}

export class DisputeResolutionService {
  /**
   * Initiate dispute (Stage 1: Bilateral negotiation)
   */
  async initiateDispute(data: DisputeData) {
    const dispute = await prisma.dispute_resolutions.create({
      data: {
        id: uuidv4(),
        disputeId: uuidv4(),
        sovereignBankId1: data.sovereignBankId1,
        sovereignBankId2: data.sovereignBankId2,
        disputeType: data.disputeType,
        description: data.description,
        stage: 'bilateral',
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return dispute;
  }

  /**
   * Escalate to CAA mediation (Stage 2)
   */
  async escalateToCAAMediation(disputeId: string, reason?: string) {
    const dispute = await prisma.dispute_resolutions.findUnique({
      where: { disputeId },
    });

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

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

    const updated = await prisma.dispute_resolutions.update({
      where: { disputeId },
      data: {
        stage: 'caa_mediation',
        description: reason
          ? `${dispute.description}\n\n[Escalated to CAA: ${reason}]`
          : dispute.description,
      },
    });

    return updated;
  }

  /**
   * Escalate to binding arbitration (Stage 3)
   */
  async escalateToBindingArbitration(disputeId: string, reason?: string) {
    const dispute = await prisma.dispute_resolutions.findUnique({
      where: { disputeId },
    });

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

    if (dispute.stage !== 'caa_mediation') {
      throw new Error(
        `Dispute is not in CAA mediation stage. Current stage: ${dispute.stage}`
      );
    }

    const updated = await prisma.dispute_resolutions.update({
      where: { disputeId },
      data: {
        stage: 'binding_arbitration',
        description: reason
          ? `${dispute.description}\n\n[Escalated to Binding Arbitration: ${reason}]`
          : dispute.description,
      },
    });

    return updated;
  }

  /**
   * Resolve dispute
   */
  async resolveDispute(disputeId: string, resolution: string) {
    const dispute = await prisma.dispute_resolutions.findUnique({
      where: { disputeId },
    });

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

    if (dispute.status !== 'active') {
      throw new Error(`Dispute is not active. Current status: ${dispute.status}`);
    }

    const updated = await prisma.dispute_resolutions.update({
      where: { disputeId },
      data: {
        status: 'resolved',
        resolution,
        resolvedAt: new Date(),
      },
    });

    return updated;
  }

  /**
   * Get dispute by ID
   */
  async getDispute(disputeId: string) {
    return await prisma.dispute_resolutions.findUnique({
      where: { disputeId },
    });
  }

  /**
   * Get all disputes for a sovereign bank
   */
  async getDisputesForBank(sovereignBankId: string) {
    return await prisma.dispute_resolutions.findMany({
      where: {
        OR: [
          { sovereignBankId1: sovereignBankId },
          { sovereignBankId2: sovereignBankId },
        ],
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  /**
   * Get disputes by stage
   */
  async getDisputesByStage(stage: string) {
    return await prisma.dispute_resolutions.findMany({
      where: {
        stage,
        status: 'active',
      },
      orderBy: { createdAt: 'desc' },
    });
  }
}

export const disputeResolutionService = new DisputeResolutionService();

