// DBIS Quantum-Temporal Arbitration Engine - Affirmation Service
// Finality affirmation

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { qtaeDetectionService } from './qtae-detection.service';
import { qtaeResolutionService } from './qtae-resolution.service';


export type DecisionType = 'rollback' | 'affirm_finality' | 'partial_resolution';

export interface CreateDecisionRequest {
  arbitrationId: string;
  decisionType: DecisionType;
  decisionDetails: Record<string, unknown>;
  finality?: boolean;
}

export class QtaeAffirmationService {
  /**
   * Create arbitration decision
   */
  async createDecision(request: CreateDecisionRequest) {
    const arbitration = await qtaeDetectionService.getArbitration(request.arbitrationId);
    if (!arbitration) {
      throw new Error(`Arbitration not found: ${request.arbitrationId}`);
    }

    const decisionId = `DEC-${uuidv4()}`;

    const decision = await prisma.arbitrationDecision.create({
      data: {
        decisionId,
        arbitrationId: request.arbitrationId,
        decisionType: request.decisionType,
        decisionDetails: request.decisionDetails,
        finality: request.finality || false,
        status: 'pending',
      },
    });

    return decision;
  }

  /**
   * Affirm finality
   * Logic: if no contradiction_detected: affirm_finality()
   */
  async affirmFinality(arbitrationId: string) {
    const arbitration = await qtaeDetectionService.getArbitration(arbitrationId);
    if (!arbitration) {
      throw new Error(`Arbitration not found: ${arbitrationId}`);
    }

    const contradictions = await qtaeDetectionService.getContradictions(arbitrationId);
    const unresolved = contradictions.filter((c) => !c.resolved);

    if (unresolved.length > 0) {
      throw new Error(`Cannot affirm finality: ${unresolved.length} unresolved contradictions`);
    }

    const decision = await this.createDecision({
      arbitrationId,
      decisionType: 'affirm_finality',
      decisionDetails: {
        reason: 'No contradictions detected',
        arbitrationType: arbitration.arbitrationType,
      },
      finality: true,
    });

    // Update arbitration status
    await prisma.quantumTemporalArbitration.update({
      where: { arbitrationId },
      data: {
        status: 'resolved',
        resolvedAt: new Date(),
      },
    });

    // Execute decision
    await this.executeDecision(decision.decisionId);

    return decision;
  }

  /**
   * Execute decision
   */
  async executeDecision(decisionId: string) {
    const decision = await prisma.arbitrationDecision.findUnique({
      where: { decisionId },
      include: {
        arbitration: true,
      },
    });

    if (!decision) {
      throw new Error(`Decision not found: ${decisionId}`);
    }

    if (decision.status !== 'pending') {
      throw new Error(`Decision already ${decision.status}`);
    }

    // Update status
    await prisma.arbitrationDecision.update({
      where: { decisionId },
      data: { status: 'executed' },
    });

    // Handle decision based on type
    switch (decision.decisionType) {
      case 'rollback':
        // Rollback already handled by resolution service
        break;
      case 'affirm_finality':
        // Finality affirmed
        break;
      case 'partial_resolution':
        // Partial resolution applied
        break;
    }

    return decision;
  }

  /**
   * Get decision by ID
   */
  async getDecision(decisionId: string) {
    return await prisma.arbitrationDecision.findUnique({
      where: { decisionId },
      include: {
        arbitration: true,
      },
    });
  }

  /**
   * Get decisions for arbitration
   */
  async getDecisionsForArbitration(arbitrationId: string) {
    return await prisma.arbitrationDecision.findMany({
      where: { arbitrationId },
      orderBy: { decidedAt: 'desc' },
    });
  }

  /**
   * Get final decisions
   */
  async getFinalDecisions() {
    return await prisma.arbitrationDecision.findMany({
      where: { finality: true },
      orderBy: { decidedAt: 'desc' },
    });
  }
}

export const qtaeAffirmationService = new QtaeAffirmationService();

