// ASSS Scenario Service
// Stress test scenario management

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


export interface CreateScenarioRequest {
  scenarioName: string;
  scenarioType: string; // liquidity_shock, fx_collapse, commodity_depletion, sovereign_default
  scenarioConfig: Record<string, unknown>;
  stressLevel: string; // low, medium, high, extreme
}

export interface ScenarioResult {
  scenarioId: string;
  status: string;
}

export class AsssScenarioService {
  /**
   * Create scenario
   */
  async createScenario(request: CreateScenarioRequest): Promise<ScenarioResult> {
    const scenarioId = `ASSS-SCENARIO-${uuidv4()}`;

    const scenario = await prisma.simulationScenario.create({
      data: {
        scenarioId,
        scenarioName: request.scenarioName,
        scenarioType: request.scenarioType,
        scenarioConfig: request.scenarioConfig,
        stressLevel: request.stressLevel,
        status: 'active',
      },
    });

    return {
      scenarioId: scenario.scenarioId,
      status: scenario.status,
    };
  }

  /**
   * Link scenario to simulation
   */
  async linkScenario(simulationId: string, scenarioId: string): Promise<void> {
    // Verify scenario exists
    const scenario = await prisma.simulationScenario.findUnique({
      where: { scenarioId },
    });

    if (!scenario) {
      throw new Error(`Scenario not found: ${scenarioId}`);
    }

    // Update scenario with simulation ID
    await prisma.simulationScenario.update({
      where: { scenarioId },
      data: {
        simulationId,
      },
    });
  }

  /**
   * Get scenario
   */
  async getScenario(scenarioId: string) {
    return await prisma.simulationScenario.findUnique({
      where: { scenarioId },
      include: {
        simulation: true,
      },
    });
  }

  /**
   * List scenarios
   */
  async listScenarios(scenarioType?: string, stressLevel?: string) {
    return await prisma.simulationScenario.findMany({
      where: {
        ...(scenarioType ? { scenarioType } : {}),
        ...(stressLevel ? { stressLevel } : {}),
      },
      orderBy: { createdAt: 'desc' },
    });
  }
}

export const asssScenarioService = new AsssScenarioService();

