// Wallet Accounts Service
// Manages stored value accounts with sub-ledgers

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

export interface WalletAccount {
  id: string;
  walletId: string;
  userId: string;
  currencyCode: string;
  balance: string;
  availableBalance: string;
  status: 'active' | 'suspended' | 'closed';
  createdAt: Date;
  updatedAt: Date;
}

export interface CreateWalletRequest {
  tenantId: string;
  programId?: string;
  userId: string;
  currencyCode: string;
  initialBalance?: string;
}

export interface WalletTransferRequest {
  tenantId: string;
  fromWalletId: string;
  toWalletId: string;
  amount: string;
  currencyCode: string;
  description?: string;
}

export class WalletAccountsService {
  /**
   * Create a wallet account
   */
  async createWallet(request: CreateWalletRequest): Promise<WalletAccount> {
    await requireCapability('wallet-accounts', {
      tenantId: request.tenantId,
      programId: request.programId,
      capabilityId: 'wallet-accounts',
      channel: 'API',
    });

    const wallet: WalletAccount = {
      id: uuidv4(),
      walletId: `WALLET-${uuidv4()}`,
      userId: request.userId,
      currencyCode: request.currencyCode,
      balance: request.initialBalance || '0',
      availableBalance: request.initialBalance || '0',
      status: 'active',
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    logger.info(`Wallet created`, { walletId: wallet.walletId });
    return wallet;
  }

  /**
   * Get wallet by ID
   */
  async getWallet(walletId: string, tenantId: string): Promise<WalletAccount | null> {
    await requireCapability('wallet-accounts', {
      tenantId,
      capabilityId: 'wallet-accounts',
      channel: 'API',
    });
    // In production, fetch from database
    return null;
  }

  /**
   * Transfer between wallets (P2P)
   */
  async transfer(request: WalletTransferRequest): Promise<void> {
    await requireCapability('p2p-transfers', {
      tenantId: request.tenantId,
      capabilityId: 'p2p-transfers',
      channel: 'API',
    });

    // Post to ledger
    await ledgerPostingAPI.postEntries({
      referenceId: uuidv4(),
      entries: [
        {
          debitAccountId: request.fromWalletId,
          creditAccountId: request.toWalletId,
          amount: request.amount,
          currencyCode: request.currencyCode,
          assetType: 'fiat',
          description: request.description,
        },
      ],
      transactionType: 'TYPE_A',
      metadata: {
        type: 'wallet_transfer',
        fromWalletId: request.fromWalletId,
        toWalletId: request.toWalletId,
      },
    });

    logger.info(`Wallet transfer completed`, {
      fromWalletId: request.fromWalletId,
      toWalletId: request.toWalletId,
      amount: request.amount,
    });
  }
}

export const walletAccountsService = new WalletAccountsService();
