# 🏗️ Enamel Wallets - Account Management & Integration Strategy

## 📋 Executive Summary

For Enamel Wallets as a Nigerian cooperative, we recommend a **hybrid architecture** that maintains direct user relationships while leveraging strategic 3rd party integrations for enhanced functionality.

## 🎯 Recommended Approach: Internal Accounts + Strategic Integrations

### 1. 🔐 Core User Management (Internal)

**Users should have direct accounts with Enamel Wallets:**

```typescript
// Enhanced User Account Structure
interface EnamelUser {
  // Core Identity
  id: string;
  membershipNumber: string; // Unique cooperative member ID
  
  // Personal Information
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  bvn?: string; // Bank Verification Number
  
  // Account Status
  status: 'active' | 'suspended' | 'pending_kyc';
  kycLevel: 'tier1' | 'tier2' | 'tier3';
  role: 'member' | 'staff' | 'admin';
  
  // Cooperative Details
  joinedDate: Date;
  membershipType: 'individual' | 'corporate';
  guarantors?: UserReference[];
  
  // Financial Profile
  wallets: Wallet[];
  creditScore?: number;
  riskProfile: 'low' | 'medium' | 'high';
  
  // Verification
  isEmailVerified: boolean;
  isPhoneVerified: boolean;
  isBvnVerified: boolean;
  
  // Preferences
  preferences: UserPreferences;
  
  // Audit
  createdAt: Date;
  updatedAt: Date;
  lastActivity: Date;
}

interface Wallet {
  id: string;
  userId: string;
  type: 'daily_savings' | 'property_savings' | 'custom' | 'group' | 'spending';
  accountNumber: string; // Virtual account number
  balance: number;
  currency: 'NGN';
  status: 'active' | 'locked' | 'closed';
  
  // Wallet-specific configuration
  savingsGoal?: number;
  dailyContribution?: number;
  lockPeriod?: number;
  groupId?: string;
  
  // Banking integration
  linkedBankAccounts: LinkedAccount[];
  
  createdAt: Date;
  updatedAt: Date;
}
```

### 2. 🏦 Strategic Banking Integrations

**For Nigerian banking, integrate with these services:**

#### A. Primary Bank Integration (Recommended: Paystack or Flutterwave)
```typescript
// Bank Account Linking
interface BankIntegration {
  provider: 'paystack' | 'flutterwave' | 'interswitch';
  
  // Virtual Account Numbers (VAN) for each wallet
  virtualAccounts: {
    daily_savings: VirtualAccount;
    property_savings: VirtualAccount;
    spending: VirtualAccount;
    // Each user gets multiple VANs for different wallets
  };
  
  // Direct bank connections
  linkedAccounts: LinkedBankAccount[];
}

interface VirtualAccount {
  accountNumber: string;
  bankName: string;
  accountName: string; // "John Doe - Daily Savings"
  provider: string;
  isActive: boolean;
}

interface LinkedBankAccount {
  id: string;
  userId: string;
  bankCode: string;
  accountNumber: string;
  accountName: string;
  isVerified: boolean;
  isPrimary: boolean;
}
```

#### B. KYC & Identity Verification
```typescript
// KYC Integration
interface KYCIntegration {
  provider: 'prembly' | 'youverify' | 'identitypass';
  
  verifications: {
    bvn: BVNVerification;
    nin: NINVerification;
    phoneOtp: PhoneVerification;
    faceMatch: FaceVerification;
    addressVerification: AddressVerification;
  };
}
```

### 3. 💳 Payment Processing Integration

```typescript
// Multi-provider payment system
interface PaymentIntegration {
  // Primary: Paystack or Flutterwave
  primary: {
    provider: 'paystack' | 'flutterwave';
    capabilities: [
      'virtual_accounts',
      'transfers',
      'bill_payments',
      'card_processing'
    ];
  };
  
  // Secondary: For redundancy
  secondary: {
    provider: 'interswitch' | 'paystack' | 'flutterwave';
    capabilities: ['transfers', 'bill_payments'];
  };
  
  // Utility payments
  utilities: {
    provider: 'baxi' | 'vtpass' | 'quickteller';
    services: [
      'airtime',
      'data',
      'electricity',
      'cable_tv',
      'internet'
    ];
  };
}
```

## 🛡️ Enhanced Security & Compliance

### 1. Multi-Factor Authentication
```typescript
interface SecurityConfig {
  mfa: {
    sms: boolean;
    email: boolean;
    biometric: boolean;
    totp: boolean; // Google Authenticator
  };
  
  sessionManagement: {
    timeout: number; // minutes
    concurrentSessions: number;
    ipWhitelisting: boolean;
  };
  
  transactionLimits: {
    daily: number;
    monthly: number;
    perTransaction: number;
    requiresApproval: number; // Amount requiring additional approval
  };
}
```

### 2. Audit & Compliance
```typescript
interface ComplianceSystem {
  aml: {
    provider: 'identitypass' | 'youverify';
    screening: 'realtime' | 'batch';
    watchlistCheck: boolean;
  };
  
  auditLog: {
    allTransactions: boolean;
    userActions: boolean;
    adminActions: boolean;
    systemEvents: boolean;
    retention: number; // years
  };
  
  reporting: {
    regulatory: 'cbn' | 'firs' | 'efcc';
    frequency: 'daily' | 'weekly' | 'monthly';
    automated: boolean;
  };
}
```

## 🔄 Implementation Strategy

### Phase 1: Foundation (Weeks 1-4)
1. **User Account System**
   - Implement enhanced user model
   - Set up Supabase database with proper schemas
   - Add role-based access control

2. **KYC Integration**
   - Integrate with Prembly or YouVerify
   - Implement tier-based verification
   - Add document upload and verification

### Phase 2: Banking Integration (Weeks 5-8)
1. **Virtual Account Numbers**
   - Integrate with Paystack Virtual Accounts
   - Generate unique VANs for each wallet type
   - Set up automatic balance updates

2. **Bank Account Linking**
   - Add bank account verification
   - Implement account linking flow
   - Set up transfer capabilities

### Phase 3: Enhanced Features (Weeks 9-12)
1. **Payment Processing**
   - Add bill payment integration (Baxi/VTPass)
   - Implement P2P transfers
   - Add transaction history and receipts

2. **Security & Compliance**
   - Implement MFA system
   - Add transaction monitoring
   - Set up audit logging

## 💾 Database Schema Updates

### Enhanced Supabase Schema
```sql
-- Users table (enhanced)
CREATE TABLE users (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  membership_number VARCHAR(20) UNIQUE NOT NULL,
  first_name VARCHAR(100) NOT NULL,
  last_name VARCHAR(100) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL,
  phone VARCHAR(20) UNIQUE NOT NULL,
  bvn VARCHAR(11),
  status VARCHAR(20) DEFAULT 'pending_kyc',
  kyc_level VARCHAR(10) DEFAULT 'tier1',
  role VARCHAR(20) DEFAULT 'member',
  joined_date TIMESTAMP DEFAULT NOW(),
  membership_type VARCHAR(20) DEFAULT 'individual',
  is_email_verified BOOLEAN DEFAULT FALSE,
  is_phone_verified BOOLEAN DEFAULT FALSE,
  is_bvn_verified BOOLEAN DEFAULT FALSE,
  risk_profile VARCHAR(10) DEFAULT 'low',
  preferences JSONB DEFAULT '{}',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW(),
  last_activity TIMESTAMP DEFAULT NOW()
);

-- Wallets table
CREATE TABLE wallets (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  type VARCHAR(50) NOT NULL,
  account_number VARCHAR(20) UNIQUE NOT NULL,
  balance DECIMAL(15,2) DEFAULT 0.00,
  currency VARCHAR(3) DEFAULT 'NGN',
  status VARCHAR(20) DEFAULT 'active',
  savings_goal DECIMAL(15,2),
  daily_contribution DECIMAL(15,2),
  lock_period INTEGER,
  group_id UUID,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Virtual accounts for banking integration
CREATE TABLE virtual_accounts (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  wallet_id UUID REFERENCES wallets(id) ON DELETE CASCADE,
  provider VARCHAR(50) NOT NULL,
  account_number VARCHAR(20) NOT NULL,
  bank_name VARCHAR(100) NOT NULL,
  account_name VARCHAR(200) NOT NULL,
  is_active BOOLEAN DEFAULT TRUE,
  created_at TIMESTAMP DEFAULT NOW()
);

-- Linked bank accounts
CREATE TABLE linked_bank_accounts (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  bank_code VARCHAR(10) NOT NULL,
  account_number VARCHAR(20) NOT NULL,
  account_name VARCHAR(200) NOT NULL,
  is_verified BOOLEAN DEFAULT FALSE,
  is_primary BOOLEAN DEFAULT FALSE,
  created_at TIMESTAMP DEFAULT NOW()
);

-- Transactions
CREATE TABLE transactions (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID REFERENCES users(id),
  wallet_id UUID REFERENCES wallets(id),
  type VARCHAR(50) NOT NULL,
  amount DECIMAL(15,2) NOT NULL,
  fee DECIMAL(15,2) DEFAULT 0.00,
  status VARCHAR(20) DEFAULT 'pending',
  reference VARCHAR(100) UNIQUE NOT NULL,
  description TEXT,
  metadata JSONB DEFAULT '{}',
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- KYC verifications
CREATE TABLE kyc_verifications (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  user_id UUID REFERENCES users(id) ON DELETE CASCADE,
  verification_type VARCHAR(50) NOT NULL,
  provider VARCHAR(50) NOT NULL,
  status VARCHAR(20) DEFAULT 'pending',
  reference VARCHAR(100),
  data JSONB DEFAULT '{}',
  verified_at TIMESTAMP,
  created_at TIMESTAMP DEFAULT NOW()
);
```

## 📱 Frontend Integration Updates

### Enhanced Authentication Flow
```typescript
// utils/auth.ts (enhanced)
export interface AuthConfig {
  multiFactorAuth: boolean;
  biometricAuth: boolean;
  sessionTimeout: number;
  maxConcurrentSessions: number;
}

export class EnhancedAuthService {
  static async signUp(userData: SignUpData): Promise<AuthResult> {
    // 1. Create user account
    const user = await supabase.auth.signUp({
      email: userData.email,
      password: userData.password,
      options: {
        data: {
          first_name: userData.firstName,
          last_name: userData.lastName,
          phone: userData.phone,
          membership_number: await this.generateMembershipNumber()
        }
      }
    });

    // 2. Initialize default wallets
    if (user.data.user) {
      await this.createDefaultWallets(user.data.user.id);
      
      // 3. Generate virtual account numbers
      await this.setupVirtualAccounts(user.data.user.id);
      
      // 4. Send verification SMS/Email
      await this.sendVerificationCodes(user.data.user);
    }

    return user;
  }

  static async createDefaultWallets(userId: string) {
    const defaultWallets = [
      { type: 'spending', name: 'Spending Wallet' },
      { type: 'daily_savings', name: 'Daily Savings' },
      { type: 'property_savings', name: 'Property Savings' }
    ];

    for (const wallet of defaultWallets) {
      await supabase.from('wallets').insert({
        user_id: userId,
        type: wallet.type,
        account_number: await this.generateAccountNumber(),
        balance: 0.00
      });
    }
  }

  static async setupVirtualAccounts(userId: string) {
    // Integrate with Paystack/Flutterwave to create virtual accounts
    const wallets = await supabase
      .from('wallets')
      .select('*')
      .eq('user_id', userId);

    for (const wallet of wallets.data || []) {
      await PaymentService.createVirtualAccount(wallet);
    }
  }
}
```

## 🤝 Recommended Service Providers (Nigeria)

### Banking & Payments
1. **Primary: Paystack** 
   - Virtual accounts ✅
   - Transfers ✅ 
   - Bill payments ✅
   - Excellent Nigerian market presence

2. **Secondary: Flutterwave**
   - Backup payment processing
   - International capabilities
   - Good API documentation

### KYC & Verification
1. **Primary: Prembly**
   - BVN verification
   - NIN verification
   - Address verification
   - Nigerian regulatory compliance

2. **Secondary: YouVerify**
   - Identity verification
   - Document verification
   - AML screening

### Utilities & Bills
1. **Baxi** - Comprehensive bill payment
2. **VTPass** - Alternative for utilities
3. **Quickteller** - Bank-backed bill payments

## 💰 Cost Estimation

### Monthly Operational Costs (1000+ users):
- **Paystack**: ₦1.5% per transaction + ₦100 cap
- **Prembly KYC**: ₦100-500 per verification
- **SMS**: ₦10-20 per message
- **Supabase**: $25-100/month for database
- **Virtual Accounts**: ₦50-100 per account/month

### Revenue Model:
- **Group Savings Fee**: 1% of payout amount
- **Express Transfer**: ₦50 per transaction
- **Bill Payment Commission**: 0.5-1% of transaction
- **Membership Fee**: ₦1,000-5,000 annually

## 🎯 Next Steps

1. **Week 1-2**: Set up enhanced Supabase schema
2. **Week 3-4**: Integrate Paystack virtual accounts
3. **Week 5-6**: Add Prembly KYC verification
4. **Week 7-8**: Implement bill payment integration
5. **Week 9-10**: Add enhanced security features
6. **Week 11-12**: Testing and compliance review

This hybrid approach gives you the best of both worlds: direct customer relationships with your cooperative members while leveraging proven Nigerian fintech infrastructure for banking and payments.