// DBIS Quantum-Temporal Arbitration Engine - Notification Service
// MSA notification system

import prisma from '@/shared/database/prisma';
import { qtaeAffirmationService } from './qtae-affirmation.service';


export class QtaeNotificationService {
  /**
   * Notify MSA (Meta-Sovereign Authority) of arbitration decision
   */
  async notifyMSA(decisionId: string) {
    const decision = await qtaeAffirmationService.getDecision(decisionId);
    if (!decision) {
      throw new Error(`Decision not found: ${decisionId}`);
    }

    // In production, this would send notification to MSA
    // For now, just mark as notified

    await prisma.arbitrationDecision.update({
      where: { decisionId },
      data: {
        msaNotified: true,
        msaNotificationAt: new Date(),
      },
    });

    return {
      decisionId,
      msaNotified: true,
      notificationAt: new Date(),
    };
  }

  /**
   * Get decisions pending MSA notification
   */
  async getDecisionsPendingMSANotification() {
    return await prisma.arbitrationDecision.findMany({
      where: {
        msaNotified: false,
        finality: true,
      },
      orderBy: { decidedAt: 'asc' },
      include: {
        arbitration: true,
      },
    });
  }

  /**
   * Notify MSA of all pending decisions
   */
  async notifyMSAOfAllPending() {
    const pending = await this.getDecisionsPendingMSANotification();

    const results = await Promise.all(
      pending.map((decision) =>
        this.notifyMSA(decision.decisionId).catch((err) => ({
          decisionId: decision.decisionId,
          error: err.message,
        }))
      )
    );

    return {
      total: pending.length,
      notified: results.filter((r) => !('error' in r)).length,
      failed: results.filter((r) => 'error' in r).length,
      results,
    };
  }

  /**
   * Get notification status
   */
  async getNotificationStatus(decisionId: string) {
    const decision = await qtaeAffirmationService.getDecision(decisionId);
    if (!decision) {
      throw new Error(`Decision not found: ${decisionId}`);
    }

    return {
      decisionId,
      msaNotified: decision.msaNotified,
      notificationAt: decision.msaNotificationAt,
      finality: decision.finality,
    };
  }
}

export const qtaeNotificationService = new QtaeNotificationService();

