// Card Issuing Service
// Handles virtual and physical card issuance

import { v4 as uuidv4 } from 'uuid';
import { requireCapability } from '@/shared/solacenet/sdk';
import { riskRulesEngine } from '@/core/risk/rules-engine.service';
import { DbisError, ErrorCode } from '@/shared/types';
import { logger } from '@/infrastructure/monitoring/logger';

export interface Card {
  id: string;
  cardId: string;
  userId: string;
  accountId: string;
  cardType: 'virtual' | 'physical';
  status: 'pending' | 'active' | 'frozen' | 'cancelled';
  last4: string;
  expiryMonth: number;
  expiryYear: number;
  createdAt: Date;
  updatedAt: Date;
}

export interface CreateCardRequest {
  tenantId: string;
  programId?: string;
  userId: string;
  accountId: string;
  cardType: 'virtual' | 'physical';
}

export interface CardControlRequest {
  tenantId: string;
  cardId: string;
  action: 'freeze' | 'unfreeze' | 'cancel';
}

export class CardIssuingService {
  /**
   * Issue a new card
   */
  async issueCard(request: CreateCardRequest): Promise<Card> {
    await requireCapability('card-issuing', {
      tenantId: request.tenantId,
      programId: request.programId,
      capabilityId: 'card-issuing',
      channel: 'API',
    });

    // Risk assessment
    const riskAssessment = await riskRulesEngine.assessRisk({
      userId: request.userId,
      amount: '0',
      currencyCode: 'USD',
      context: {
        action: 'card_issuance',
        cardType: request.cardType,
      },
    });

    if (riskAssessment.decision === 'block') {
      throw new DbisError(ErrorCode.FORBIDDEN, 'Card issuance blocked due to risk assessment');
    }

    const card: Card = {
      id: uuidv4(),
      cardId: `CARD-${uuidv4()}`,
      userId: request.userId,
      accountId: request.accountId,
      cardType: request.cardType,
      status: 'pending',
      last4: this.generateLast4(),
      expiryMonth: new Date().getMonth() + 1,
      expiryYear: new Date().getFullYear() + 3,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    logger.info(`Card issued`, { cardId: card.cardId, cardType: request.cardType });
    return card;
  }

  /**
   * Control card (freeze, unfreeze, cancel)
   */
  async controlCard(request: CardControlRequest): Promise<void> {
    await requireCapability('card-controls', {
      tenantId: request.tenantId,
      capabilityId: 'card-controls',
      channel: 'API',
    });

    logger.info(`Card control action`, {
      cardId: request.cardId,
      action: request.action,
    });
  }

  /**
   * Generate last 4 digits
   */
  private generateLast4(): string {
    return Math.floor(1000 + Math.random() * 9000).toString();
  }
}

export const cardIssuingService = new CardIssuingService();
