// DBIS Admin Console - GRU Controls Service
// GRU issuance, locks, circuit breakers, bond issuance windows

import { Prisma } from '@prisma/client';
import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';
import { v4 as uuidv4 } from 'uuid';
import { adminAuditService } from '@/core/admin/shared/admin-audit.service';
import { AdminPermission } from '@/core/admin/shared/permissions.constants';

export interface GRUIssuanceProposal {
  gruClass: string; // M00, M0, M1, SR-1, SR-2, SR-3
  amount: number;
  reason: string;
  effectiveDate?: Date;
}

export interface GRULockRequest {
  gruClass: string;
  action: 'lock' | 'unlock';
  reason: string;
}

export interface GRUCircuitBreakerConfig {
  indexId: string;
  maxIntradayMove: number; // e.g., 0.05 for 5%
  enabled: boolean;
}

export interface GRUBondIssuanceWindow {
  bondId: string;
  action: 'open' | 'close';
  reason?: string;
}

export class GRUControlsService {
  /**
   * Create GRU issuance proposal
   */
  async createIssuanceProposal(
    employeeId: string,
    proposal: GRUIssuanceProposal
  ): Promise<{ proposalId: string; status: string }> {
    // Log action
    await adminAuditService.logAction({
      employeeId,
      action: 'create_gru_issuance_proposal',
      permission: AdminPermission.GRU_ISSUANCE_PROPOSAL,
      resourceType: 'gru_issuance',
      metadata: proposal as unknown as Record<string, unknown>,
    });

    // Create proposal (would go through governance workflow)
    const proposalId = uuidv4();

    logger.info('GRU issuance proposal created', {
      proposalId,
      employeeId,
      proposal,
    });

    return {
      proposalId,
      status: 'pending_governance_approval',
    };
  }

  /**
   * Lock or unlock GRU class
   */
  async lockUnlockGRUClass(
    employeeId: string,
    request: GRULockRequest
  ): Promise<{ success: boolean; message: string }> {
    await adminAuditService.logAction({
      employeeId,
      action: request.action === 'lock' ? 'lock_gru_class' : 'unlock_gru_class',
      permission: AdminPermission.GRU_LOCK_UNLOCK,
      resourceType: 'gru_class',
      resourceId: request.gruClass,
      metadata: request as unknown as Record<string, unknown>,
    });

    // Update GRU unit status (placeholder - would need proper implementation)
    logger.info('GRU class lock/unlock', {
      employeeId,
      request,
    });

    return {
      success: true,
      message: `GRU class ${request.gruClass} ${request.action === 'lock' ? 'locked' : 'unlocked'}`,
    };
  }

  /**
   * Set circuit breakers for GRU index
   */
  async setCircuitBreakers(
    employeeId: string,
    config: GRUCircuitBreakerConfig
  ): Promise<{ success: boolean }> {
    await adminAuditService.logAction({
      employeeId,
      action: 'set_gru_circuit_breakers',
      permission: AdminPermission.GRU_CIRCUIT_BREAKERS,
      resourceType: 'gru_index',
      resourceId: config.indexId,
      beforeState: {},
      afterState: config as unknown as Record<string, unknown>,
    });

    // Update GRU index
    // Note: circuitBreakerEnabled and circuitBreakerThreshold fields don't exist in schema
    // These would need to be stored in metadata or a separate table
    await prisma.gru_indexes.updateMany({
      where: { indexId: config.indexId },
      data: {
        // circuitBreakerEnabled: config.enabled,
        // circuitBreakerThreshold: config.maxIntradayMove,
        updatedAt: new Date(),
      },
    });

    return { success: true };
  }

  /**
   * Open or close GRU bond issuance window
   */
  async manageBondIssuanceWindow(
    employeeId: string,
    request: GRUBondIssuanceWindow
  ): Promise<{ success: boolean }> {
    await adminAuditService.logAction({
      employeeId,
      action: request.action === 'open' ? 'open_bond_issuance_window' : 'close_bond_issuance_window',
      permission: AdminPermission.GRU_BOND_ISSUANCE_WINDOW,
      resourceType: 'gru_bond',
      resourceId: request.bondId,
      metadata: request as unknown as Record<string, unknown>,
    });

    // Update bond
    // Note: issuanceWindowOpen field doesn't exist in schema
    // This would need to be stored in metadata or a separate table
    await prisma.gru_bonds.updateMany({
      where: { bondId: request.bondId },
      data: {
        // issuanceWindowOpen: request.action === 'open',
        updatedAt: new Date(),
      },
    });

    return { success: true };
  }

  /**
   * Trigger emergency buy-back
   */
  async triggerEmergencyBuyback(
    employeeId: string,
    bondId: string,
    amount: number
  ): Promise<{ success: boolean; transactionId: string }> {
    await adminAuditService.logAction({
      employeeId,
      action: 'trigger_emergency_buyback',
      permission: AdminPermission.GRU_BOND_BUYBACK,
      resourceType: 'gru_bond',
      resourceId: bondId,
      metadata: { amount },
    });

    // Would require multi-sig/governance confirmation in production
    const transactionId = uuidv4();

    logger.warn('Emergency buy-back triggered', {
      employeeId,
      bondId,
      amount,
      transactionId,
    });

    return { success: true, transactionId };
  }
}

export const gruControlsService = new GRUControlsService();

