# 🚀 Enamel Wallets Deployment Guide

## 📋 **Pre-Deployment Checklist**

### **1. Environment Setup**
```bash
# Create production environment variables
cp .env.example .env.production
```

### **2. Required Environment Variables**
```env
# Supabase Configuration
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# API Keys (get these from providers)
VITE_PAYSTACK_PUBLIC_KEY=pk_live_your-paystack-public-key
PAYSTACK_SECRET_KEY=sk_live_your-paystack-secret-key
PREMBLY_API_KEY=your-prembly-api-key
TERMII_API_KEY=your-termii-api-key

# App Configuration
VITE_APP_NAME=Enamel Wallets
VITE_APP_URL=https://app.enamelwallets.ng
VITE_API_URL=https://your-project.supabase.co/functions/v1

# Security
JWT_SECRET=your-super-secure-jwt-secret
ENCRYPTION_KEY=your-32-character-encryption-key

# Nigerian Banking
NIBSS_API_KEY=your-nibss-api-key
CBN_API_KEY=your-cbn-api-key
```

---

## 🌐 **Step 1: Frontend Deployment (Vercel - Recommended)**

### **Deploy with Vercel:**
```bash
# 1. Install Vercel CLI
npm i -g vercel

# 2. Login to Vercel
vercel login

# 3. Deploy from your project root
vercel

# 4. Follow the prompts:
# ✓ Link to existing project? No
# ✓ Project name: enamel-wallets
# ✓ Directory: ./
# ✓ Build command: npm run build
# ✓ Output directory: dist
# ✓ Development command: npm run dev
```

### **Environment Variables in Vercel:**
```bash
# Add each environment variable
vercel env add VITE_SUPABASE_URL
vercel env add VITE_SUPABASE_ANON_KEY
vercel env add VITE_PAYSTACK_PUBLIC_KEY
# ... add all required variables

# Re-deploy with new environment variables
vercel --prod
```

### **Custom Domain Setup:**
```bash
# Add your custom domain
vercel domains add app.enamelwallets.ng
vercel domains add enamelwallets.ng

# Configure DNS (in your domain registrar):
# A record: @ → 76.76.19.19
# CNAME record: www → cname.vercel-dns.com
# CNAME record: app → cname.vercel-dns.com
```

---

## 🗄️ **Step 2: Backend Setup (Supabase)**

### **Database Setup:**
1. **Go to your Supabase Dashboard**
2. **SQL Editor → New Query**
3. **Paste the entire `DATABASE_SCHEMA.sql` content**
4. **Run the query**

### **Edge Functions Deployment:**
```bash
# Install Supabase CLI
npm install -g supabase

# Login to Supabase
supabase login

# Link your project
supabase link --project-ref your-project-ref

# Deploy your functions
supabase functions deploy server

# Set function secrets
supabase secrets set PAYSTACK_SECRET_KEY=your-secret-key
supabase secrets set PREMBLY_API_KEY=your-api-key
supabase secrets set TERMII_API_KEY=your-api-key
```

### **Storage Setup:**
```sql
-- Create storage buckets for documents
INSERT INTO storage.buckets (id, name, public) VALUES 
('kyc-documents', 'kyc-documents', false),
('profile-images', 'profile-images', false),
('receipts', 'receipts', false);

-- Set up storage policies
CREATE POLICY "Users can upload their KYC documents" ON storage.objects 
FOR INSERT WITH CHECK (bucket_id = 'kyc-documents' AND auth.uid()::text = (storage.foldername(name))[1]);

CREATE POLICY "Users can view their documents" ON storage.objects 
FOR SELECT USING (bucket_id = 'kyc-documents' AND auth.uid()::text = (storage.foldername(name))[1]);
```

---

## 🔐 **Step 3: Security Configuration**

### **Authentication Setup:**
```sql
-- Enable email confirmation
UPDATE auth.config SET email_confirm = true;

-- Set JWT expiry
UPDATE auth.config SET jwt_exp = 3600;

-- Enable MFA
UPDATE auth.config SET mfa_enabled = true;
```

### **API Rate Limiting:**
```typescript
// Add to your edge function
import { createClient } from '@supabase/supabase-js'

const rateLimiter = new Map();

export const rateLimitMiddleware = (req: Request) => {
  const ip = req.headers.get('x-forwarded-for') || req.headers.get('remote-addr');
  const key = `rate_limit:${ip}`;
  
  const requests = rateLimiter.get(key) || 0;
  if (requests > 100) { // 100 requests per hour
    return new Response('Rate limit exceeded', { status: 429 });
  }
  
  rateLimiter.set(key, requests + 1);
  setTimeout(() => rateLimiter.delete(key), 3600000); // 1 hour
};
```

---

## 📱 **Step 4: Progressive Web App (PWA) Setup**

### **Add PWA Configuration:**
```json
// public/manifest.json
{
  "name": "Enamel Wallets",
  "short_name": "Enamel",
  "description": "Nigerian Cooperative Fintech Platform",
  "start_url": "/",
  "display": "standalone",
  "background_color": "#0f172a",
  "theme_color": "#0066cc",
  "orientation": "portrait",
  "categories": ["finance", "productivity"],
  "screenshots": [
    {
      "src": "/screenshots/mobile-dashboard.png",
      "sizes": "390x844",
      "type": "image/png",
      "form_factor": "narrow"
    }
  ],
  "icons": [
    {
      "src": "/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}
```

---

## 🧪 **Step 5: Testing Strategy**

### **Create Test User Accounts:**
```sql
-- Insert test users for different scenarios
INSERT INTO public.users (
  id, email, phone, first_name, last_name, 
  account_number, membership_number, role, kyc_status
) VALUES 
(
  '00000000-0000-0000-0000-000000000001',
  'test@enamelwallets.ng',
  '+2348012345678',
  'Test',
  'User',
  '3012345678',
  'EMW-2024-000001',
  'customer',
  'verified'
),
(
  '00000000-0000-0000-0000-000000000002', 
  'admin@enamelwallets.ng',
  '+2348012345679',
  'Admin',
  'User',
  '3012345679',
  'EMW-2024-000002',
  'admin',
  'verified'
);

-- Create test wallets
INSERT INTO public.wallets (
  user_id, wallet_type, name, account_number, balance
) VALUES
(
  '00000000-0000-0000-0000-000000000001',
  'spending',
  'Main Spending',
  '3012345678',
  1000000 -- ₦10,000 in kobo
),
(
  '00000000-0000-0000-0000-000000000001',
  'daily_savings', 
  'Daily Savings',
  '3012345680',
  500000 -- ₦5,000 in kobo
);
```

### **Test Credentials for Users:**
```markdown
## 🧪 Test Accounts

### Regular User
- Email: `test@enamelwallets.ng`
- Password: `TestUser123!`
- Phone: `+2348012345678`
- Account: `3012345678`

### Admin User  
- Email: `admin@enamelwallets.ng`
- Password: `AdminUser123!`
- Phone: `+2348012345679`
- Account: `3012345679`

### Test Features
✅ Sign up/Sign in
✅ Dashboard navigation
✅ Wallet creation
✅ Mock transactions
✅ Group savings
✅ Bill payments (test mode)
✅ Admin panel (admin user)
```

---

## 🔍 **Step 6: Monitoring & Analytics**

### **Add Analytics:**
```typescript
// utils/analytics.ts - Already exists, configure:
export const initAnalytics = () => {
  // Google Analytics 4
  gtag('config', 'G-YOUR-GA4-ID');
  
  // User properties
  gtag('config', 'G-YOUR-GA4-ID', {
    user_properties: {
      fintech_tier: 'cooperative',
      market: 'nigeria'
    }
  });
};

// Track key fintech events
export const trackTransaction = (type: string, amount: number) => {
  gtag('event', 'transaction', {
    transaction_type: type,
    value: amount,
    currency: 'NGN'
  });
};
```

### **Error Monitoring:**
```bash
# Install Sentry
npm install @sentry/react @sentry/tracing

# Configure in your App.tsx
import * as Sentry from "@sentry/react";

Sentry.init({
  dsn: "your-sentry-dsn",
  environment: "production",
  tracesSampleRate: 1.0,
});
```

---

## 🚦 **Step 7: Go Live Checklist**

### **Pre-Launch:**
- [ ] Database schema deployed and tested
- [ ] All environment variables configured
- [ ] SSL certificates installed  
- [ ] Domain configured and working
- [ ] Test transactions working
- [ ] Admin panel accessible
- [ ] Error monitoring setup
- [ ] Backup procedures tested

### **Launch:**
- [ ] Deploy to production
- [ ] Run smoke tests
- [ ] Monitor error rates
- [ ] Check all integrations
- [ ] Verify payment flows

### **Post-Launch:**
- [ ] Monitor user signups
- [ ] Track transaction success rates  
- [ ] Monitor API performance
- [ ] Set up alerts for critical issues
- [ ] Prepare user support channels

---

## 🎯 **Quick Launch Commands**

```bash
# Complete deployment in one go
npm run build
vercel --prod
supabase functions deploy server
supabase db push

# Your app will be live at:
# https://enamel-wallets.vercel.app (or your custom domain)
```

---

## 📞 **Support & Monitoring URLs**

Once deployed, you'll have:
- **App:** `https://app.enamelwallets.ng`
- **Admin:** `https://app.enamelwallets.ng/admin`
- **API:** `https://your-project.supabase.co/functions/v1`
- **Database:** Supabase Dashboard
- **Monitoring:** Vercel Analytics + Sentry

**Your Enamel Wallets platform will be ready for public testing! 🎉**