// ASSS Simulation Service
// Simulation orchestration across layers

import prisma from '@/shared/database/prisma';
import { v4 as uuidv4 } from 'uuid';
import { asssModelService } from './asss-model.service';
import { asssScenarioService } from './asss-scenario.service';


export interface CreateSimulationRequest {
  simulationName: string;
  simulationType: string; // stress_test, policy_design, fx_band_calibration
  scenarioId?: string;
}

export interface SimulationResult {
  simulationId: string;
  status: string;
}

export class AsssSimulationService {
  /**
   * Create and start simulation
   */
  async createSimulation(request: CreateSimulationRequest): Promise<SimulationResult> {
    const simulationId = `ASSS-${uuidv4()}`;

    const simulation = await prisma.sovereign_simulations.create({
      data: {
        simulationId,
        simulationName: request.simulationName,
        simulationType: request.simulationType,
        status: 'running',
      },
    });

    // Create simulation layers
    await this.createLayers(simulationId);

    // Link scenario if provided
    if (request.scenarioId) {
      await asssScenarioService.linkScenario(simulationId, request.scenarioId);
    }

    // Start model execution
    await asssModelService.executeModel(simulationId);

    return {
      simulationId: simulation.simulationId,
      status: simulation.status,
    };
  }

  /**
   * Create simulation layers
   */
  private async createLayers(simulationId: string): Promise<void> {
    const layers = [
      {
        layerType: 'macro',
        layerConfig: {
          description: 'Global economic patterns',
          parameters: {},
        },
      },
      {
        layerType: 'sovereign',
        layerConfig: {
          description: 'SCB-specific policies',
          parameters: {},
        },
      },
      {
        layerType: 'micro',
        layerConfig: {
          description: 'Consumer and institutional behaviors',
          parameters: {},
        },
      },
      {
        layerType: 'asset',
        layerConfig: {
          description: 'Price and liquidity projections',
          parameters: {},
        },
      },
    ];

    for (const layer of layers) {
      await prisma.simulationLayer.create({
        data: {
          layerId: `ASSS-LAYER-${uuidv4()}`,
          simulationId,
          layerType: layer.layerType,
          layerConfig: layer.layerConfig,
          status: 'active',
        },
      });
    }
  }

  /**
   * Complete simulation
   */
  async completeSimulation(simulationId: string): Promise<void> {
    await prisma.sovereign_simulations.update({
      where: { simulationId },
      data: {
        status: 'completed',
        completedAt: new Date(),
      },
    });
  }

  /**
   * Get simulation
   */
  async getSimulation(simulationId: string) {
    return await prisma.sovereign_simulations.findUnique({
      where: { simulationId },
      include: {
        layers: true,
        outcomes: true,
        scenario: true,
      },
    });
  }

  /**
   * List simulations
   */
  async listSimulations(simulationType?: string) {
    return await prisma.sovereign_simulations.findMany({
      where: simulationType ? { simulationType } : undefined,
      orderBy: { startedAt: 'desc' },
    });
  }
}

export const asssSimulationService = new AsssSimulationService();

