// Payment Gateway Service
// Handles pay-in intents, captures, and refunds

import { v4 as uuidv4 } from 'uuid';
import { requireCapability } from '@/shared/solacenet/sdk';
import { ledgerPostingAPI } from '@/core/ledger/posting-api';
import { feesService } from '../fees/fees.service';
import { limitsService } from '../limits/limits.service';
import { DbisError, ErrorCode } from '@/shared/types';
import { logger } from '@/infrastructure/monitoring/logger';

export interface PaymentIntentRequest {
  tenantId: string;
  programId?: string;
  region?: string;
  channel?: string;
  amount: string;
  currencyCode: string;
  customerId: string;
  merchantId: string;
  description?: string;
  metadata?: Record<string, unknown>;
}

export interface PaymentIntent {
  id: string;
  status: 'pending' | 'succeeded' | 'failed';
  amount: string;
  currencyCode: string;
  customerId: string;
  merchantId: string;
  createdAt: Date;
}

export class PaymentGatewayService {
  /**
   * Create a payment intent
   */
  async createPaymentIntent(request: PaymentIntentRequest): Promise<PaymentIntent> {
    // Check capability
    await requireCapability('payment-gateway', {
      tenantId: request.tenantId,
      programId: request.programId,
      region: request.region,
      channel: request.channel,
      capabilityId: 'payment-gateway',
    });

    // Check limits
    const limitCheck = await limitsService.checkLimit({
      entityType: 'merchant',
      entityId: request.merchantId,
      limitType: 'transaction',
      amount: request.amount,
      currencyCode: request.currencyCode,
    });

    if (!limitCheck.allowed) {
      throw new DbisError(ErrorCode.VALIDATION_ERROR, limitCheck.reason || 'Limit exceeded');
    }

    const intent: PaymentIntent = {
      id: uuidv4(),
      status: 'pending',
      amount: request.amount,
      currencyCode: request.currencyCode,
      customerId: request.customerId,
      merchantId: request.merchantId,
      createdAt: new Date(),
    };

    logger.info(`Payment intent created`, { intentId: intent.id });
    return intent;
  }

  /**
   * Capture a payment intent
   */
  async capturePayment(intentId: string, tenantId: string): Promise<void> {
    await requireCapability('payment-gateway', {
      tenantId,
      capabilityId: 'payment-gateway',
      channel: 'API',
    });

    // In production, fetch intent, calculate fees, post to ledger
    logger.info(`Payment captured`, { intentId });
  }

  /**
   * Refund a payment
   */
  async refundPayment(paymentId: string, amount: string, tenantId: string): Promise<void> {
    await requireCapability('payment-gateway', {
      tenantId,
      capabilityId: 'payment-gateway',
      channel: 'API',
    });

    // In production, process refund, post to ledger
    logger.info(`Payment refunded`, { paymentId, amount });
  }
}

export const paymentGatewayService = new PaymentGatewayService();
