// CBDC Wallet System

import { Prisma } from '@prisma/client';
import prisma from '@/shared/database/prisma';
import { Decimal } from '@prisma/client/runtime/library';
import { CbdcWallet, CbdcWalletType } from '@/shared/types';
import { v4 as uuidv4 } from 'uuid';


export class CbdcWalletService {
  /**
   * Create CBDC wallet
   */
  async createWallet(
    sovereignBankId: string,
    walletType: CbdcWalletType,
    currencyCode: string
  ): Promise<CbdcWallet> {
    const walletId = `WALLET-${uuidv4()}`;

    const wallet = await prisma.cbdc_wallets.create({
      data: {
        id: uuidv4(),
        walletId,
        sovereignBankId,
        walletType,
        currencyCode,
        balance: new Decimal(0),
        status: 'active',
        tieredAccess: this.getDefaultTieredAccess(walletType) as Prisma.InputJsonValue,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    });

    return {
      id: wallet.id,
      walletId: wallet.walletId,
      sovereignBankId: wallet.sovereignBankId,
      walletType: wallet.walletType as CbdcWalletType,
      currencyCode: wallet.currencyCode,
      balance: wallet.balance.toString(),
      status: wallet.status,
      tieredAccess: wallet.tieredAccess as Record<string, unknown> | undefined,
    };
  }

  /**
   * Get default tiered access configuration
   */
  private getDefaultTieredAccess(walletType: CbdcWalletType): Record<string, unknown> {
    switch (walletType) {
      case CbdcWalletType.RETAIL:
        return {
          maxTransactionAmount: '10000',
          dailyLimit: '50000',
          requiresKYC: true,
        };
      case CbdcWalletType.WHOLESALE:
        return {
          maxTransactionAmount: '100000000',
          dailyLimit: '1000000000',
          requiresKYC: true,
        };
      case CbdcWalletType.INSTITUTIONAL:
        return {
          maxTransactionAmount: '1000000000',
          dailyLimit: '10000000000',
          requiresKYC: true,
          smartContractEnabled: true,
        };
      default:
        return {};
    }
  }
}

export const cbdcWalletService = new CbdcWalletService();

