// DBIS Admin Console - Corridor Controls Service
// Corridor caps, throttling, enable/disable

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { adminAuditService } from '@/core/admin/shared/admin-audit.service';
import { AdminPermission } from '@/core/admin/shared/permissions.constants';
import Decimal from 'decimal.js';

export interface CorridorCapUpdate {
  routeId: string;
  newCap: number;
  reason: string;
}

export interface CorridorThrottleRequest {
  routeId: string;
  throttleRate: number; // 0-1, where 1 = no throttling, 0.5 = 50% throttling
  reason: string;
}

export interface CorridorEnableDisable {
  routeId: string;
  action: 'enable' | 'disable';
  reason: string;
}

export class CorridorControlsService {
  /**
   * Adjust corridor caps
   */
  async adjustCorridorCaps(
    employeeId: string,
    update: CorridorCapUpdate
  ): Promise<{ success: boolean }> {
    const route = await prisma.settlementRoute.findUnique({
      where: { routeId: update.routeId },
    });

    if (!route) {
      throw new Error('Route not found');
    }

    await adminAuditService.logAction({
      employeeId,
      action: 'adjust_corridor_caps',
      permission: AdminPermission.CORRIDOR_ADJUST_CAPS,
      resourceType: 'settlement_route',
      resourceId: update.routeId,
      beforeState: { cap: route.sireCost?.toString() },
      afterState: { cap: update.newCap.toString() },
      metadata: update as Record<string, unknown>,
    });

    // Update route (would need to add cap field to schema or use existing fields)
    logger.info('Corridor cap adjusted', {
      employeeId,
      update,
    });

    return { success: true };
  }

  /**
   * Throttle corridor
   */
  async throttleCorridor(
    employeeId: string,
    request: CorridorThrottleRequest
  ): Promise<{ success: boolean }> {
    await adminAuditService.logAction({
      employeeId,
      action: 'throttle_corridor',
      permission: AdminPermission.CORRIDOR_THROTTLE,
      resourceType: 'settlement_route',
      resourceId: request.routeId,
      metadata: request as Record<string, unknown>,
    });

    // Update route status or add throttling config
    logger.info('Corridor throttled', {
      employeeId,
      request,
    });

    return { success: true };
  }

  /**
   * Enable or disable corridor
   */
  async enableDisableCorridor(
    employeeId: string,
    request: CorridorEnableDisable
  ): Promise<{ success: boolean }> {
    const route = await prisma.settlementRoute.findUnique({
      where: { routeId: request.routeId },
    });

    if (!route) {
      throw new Error('Route not found');
    }

    await adminAuditService.logAction({
      employeeId,
      action: request.action === 'enable' ? 'enable_corridor' : 'disable_corridor',
      permission: AdminPermission.CORRIDOR_ENABLE_DISABLE,
      resourceType: 'settlement_route',
      resourceId: request.routeId,
      beforeState: { status: route.status },
      afterState: { status: request.action === 'enable' ? 'active' : 'inactive' },
      metadata: request as Record<string, unknown>,
    });

    await prisma.settlementRoute.update({
      where: { routeId: request.routeId },
      data: {
        status: request.action === 'enable' ? 'active' : 'inactive',
      },
    });

    return { success: true };
  }
}

export const corridorControlsService = new CorridorControlsService();

