// AIFX Corridor Service
// Interplanetary corridor management (Earth/Luna/Mars)

import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { v4 as uuidv4 } from 'uuid';
import { InterplanetaryFxPair } from '@/shared/types';


export interface CreateCorridorRequest {
  corridorName: string;
  originPlanet: string;
  destinationPlanet: string;
  baseCurrency: string;
  quoteCurrency: string;
  lagAdjustment: string;
  gravityFactor: string;
  radiationRiskSpread: string;
  velocityNormalization: string;
}

export interface CorridorResult {
  corridorId: string;
  corridorName: string;
  originPlanet: string;
  destinationPlanet: string;
  baseCurrency: string;
  quoteCurrency: string;
  status: string;
}

export class AifxCorridorService {
  /**
   * Create an interplanetary FX corridor
   */
  async createCorridor(request: CreateCorridorRequest): Promise<CorridorResult> {
    const corridorId = `AIFX-CORR-${uuidv4()}`;

    const corridor = await prisma.aifx_corridors.create({
      data: {
        id: uuidv4(),
        corridorId,
        corridorName: request.corridorName,
        originPlanet: request.originPlanet,
        destinationPlanet: request.destinationPlanet,
        baseCurrency: request.baseCurrency,
        quoteCurrency: request.quoteCurrency,
        lagAdjustment: new Decimal(request.lagAdjustment),
        gravityFactor: new Decimal(request.gravityFactor),
        radiationRiskSpread: new Decimal(request.radiationRiskSpread),
        velocityNormalization: new Decimal(request.velocityNormalization),
        status: 'active',
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return {
      corridorId: corridor.corridorId,
      corridorName: corridor.corridorName,
      originPlanet: corridor.originPlanet,
      destinationPlanet: corridor.destinationPlanet,
      baseCurrency: corridor.baseCurrency,
      quoteCurrency: corridor.quoteCurrency,
      status: corridor.status,
    };
  }

  /**
   * Get all corridors
   */
  async getAllCorridors(includeInactive = false): Promise<InterplanetaryFxPair[]> {
    const where: { status?: string } = {};
    if (!includeInactive) {
      where.status = 'active';
    }

    const corridors = await prisma.aifx_corridors.findMany({
      where,
      orderBy: { corridorName: 'asc' },
    });

    return corridors.map((corridor) => ({
      corridorId: corridor.corridorId,
      corridorName: corridor.corridorName,
      originPlanet: corridor.originPlanet,
      destinationPlanet: corridor.destinationPlanet,
      baseCurrency: corridor.baseCurrency,
      quoteCurrency: corridor.quoteCurrency,
      lagAdjustment: corridor.lagAdjustment.toString(),
      gravityFactor: corridor.gravityFactor.toString(),
      radiationRiskSpread: corridor.radiationRiskSpread.toString(),
      velocityNormalization: corridor.velocityNormalization.toString(),
    }));
  }

  /**
   * Get corridor by planets
   */
  async getCorridorByPlanets(
    originPlanet: string,
    destinationPlanet: string
  ): Promise<InterplanetaryFxPair | null> {
    const corridor = await prisma.aifx_corridors.findFirst({
      where: {
        originPlanet,
        destinationPlanet,
        status: 'active',
      },
    });

    if (!corridor) {
      return null;
    }

    return {
      corridorId: corridor.corridorId,
      corridorName: corridor.corridorName,
      originPlanet: corridor.originPlanet,
      destinationPlanet: corridor.destinationPlanet,
      baseCurrency: corridor.baseCurrency,
      quoteCurrency: corridor.quoteCurrency,
      lagAdjustment: corridor.lagAdjustment.toString(),
      gravityFactor: corridor.gravityFactor.toString(),
      radiationRiskSpread: corridor.radiationRiskSpread.toString(),
      velocityNormalization: corridor.velocityNormalization.toString(),
    };
  }

  /**
   * Initialize default interplanetary corridors
   */
  async initializeDefaultCorridors(): Promise<void> {
    const defaultCorridors: CreateCorridorRequest[] = [
      {
        corridorName: 'Earth ↔ Luna',
        originPlanet: 'Earth',
        destinationPlanet: 'Luna',
        baseCurrency: 'USD',
        quoteCurrency: 'LUN',
        lagAdjustment: '1.003', // 0.3% latency adjustment for Earth-Luna
        gravityFactor: '0.166', // Luna gravity factor
        radiationRiskSpread: '0.002', // Small radiation risk
        velocityNormalization: '1.0',
      },
      {
        corridorName: 'Earth ↔ Mars',
        originPlanet: 'Earth',
        destinationPlanet: 'Mars',
        baseCurrency: 'USD',
        quoteCurrency: 'MRS',
        lagAdjustment: '1.050', // 5% latency adjustment for Earth-Mars
        gravityFactor: '0.378', // Mars gravity factor
        radiationRiskSpread: '0.015', // Higher radiation risk
        velocityNormalization: '1.0',
      },
      {
        corridorName: 'Mars ↔ Luna',
        originPlanet: 'Mars',
        destinationPlanet: 'Luna',
        baseCurrency: 'MRS',
        quoteCurrency: 'LUN',
        lagAdjustment: '1.047', // Latency adjustment for Mars-Luna
        gravityFactor: '0.166', // Luna gravity factor
        radiationRiskSpread: '0.010', // Medium radiation risk
        velocityNormalization: '1.0',
      },
    ];

    for (const corridorData of defaultCorridors) {
      const existing = await prisma.aifx_corridors.findFirst({
        where: {
          originPlanet: corridorData.originPlanet,
          destinationPlanet: corridorData.destinationPlanet,
        },
      });

      if (!existing) {
        await this.createCorridor(corridorData);
      }
    }
  }
}

