# Backend Migration Summary

## ✅ Completed Migrations

### 1. Authentication & Authorization
- ✅ Updated login API to return `accessToken` in nested `data` structure
- ✅ Added subscription checking in login response
- ✅ Updated middleware to support `access_token` header (with backward compatibility for `Authorization: Bearer`)
- ✅ Added user registration endpoint
- ✅ Added email verification endpoint
- ✅ Added forgot password endpoint
- ✅ Added reset password endpoint

### 2. Subscription Features (Stripe Integration)
- ✅ Created subscription controller with all functions:
  - `createPaymentIntent` - Create Stripe payment intent
  - `createSubscription` - Create subscription after payment
  - `checkActiveSubscription` - Check user's active subscription
  - `getActivePlans` - Get available subscription plans
  - `getPlanById` - Get plan details by ID
  - `cancelSubscription` - Cancel subscription
  - `reactivateSubscription` - Reactivate cancelled subscription
  - `changePlan` - Upgrade/downgrade subscription plan
  - `getSubscriptionHistory` - Get subscription history
  - `stripeWebhook` - Handle Stripe webhook events
- ✅ Created subscription routes at `/api/v1/*`
- ✅ Updated server.js to handle Stripe webhook with raw body

### 3. Utilities and Helpers
- ✅ Created `utils/appError.js` - Custom error class
- ✅ Created `utils/errorHandler.js` - Error handling middleware
- ✅ Created `helpers/DbHelper.js` - Database helper with promisifyQuery
- ✅ Created `services/db.js` - Database compatibility layer
- ✅ Created `middleware/setUserId.js` - Middleware to set user_id in headers
- ✅ Created `utils/emailService.js` - Email service for verification and password reset
- ✅ Created `utils/encryption.js` - Password hashing utilities
- ✅ Created `utils/Config.js` - Environment config helper

### 4. User & Logs Features
- ✅ Added user info endpoint
- ✅ Added user settings endpoint
- ✅ Added wallet logs endpoint
- ✅ Added purchase logs endpoint
- ✅ Added reward logs endpoint

### 5. Package Dependencies
- ✅ Added `stripe` - Stripe payment integration
- ✅ Added `moment` - Date/time manipulation
- ✅ Added `body-parser` - Request body parsing
- ✅ Added `express-session` - Session management
- ✅ Added `nodemailer` - Email sending

## 📋 New API Endpoints

### Authentication Routes (`/api/auth`)
- `POST /api/auth/login` - Login (returns accessToken with subscription info)
- `POST /api/auth/register` - User registration
- `POST /api/auth/forgot-password` - Request password reset
- `GET/POST /api/auth/reset-password` - Reset password with token
- `GET/POST /api/auth/verify-email` - Verify email with token
- `POST /api/auth/staff-login` - Staff login
- `GET /api/auth/profile` - Get user profile
- `POST /api/auth/change-password` - Change password

### Subscription Routes (`/api/v1`)
- `GET /api/v1/subscription-plans` - Get active subscription plans
- `GET /api/v1/subscription-plans/:id` - Get plan by ID
- `POST /api/v1/stripe-webhook` - Stripe webhook handler
- `POST /api/v1/create-subscription-payment` - Create payment intent
- `POST /api/v1/create-subscription` - Create subscription
- `GET /api/v1/check-active-subscription` - Check active subscription
- `POST /api/v1/cancel-subscription` - Cancel subscription
- `POST /api/v1/reactivate-subscription` - Reactivate subscription
- `POST /api/v1/change-subscription-plan` - Change subscription plan
- `GET /api/v1/subscription-history` - Get subscription history

### User Routes (`/api/v1`)
- `GET /api/v1/user-info` - Get user information
- `POST /api/v1/save-user-settings` - Save user settings
- `GET /api/v1/logs` - Get wallet logs
- `GET /api/v1/order-logs` - Get purchase logs
- `GET /api/v1/reward-logs` - Get reward logs

## 🔧 Environment Variables Required

Add these to your `.env` file:

```env
# Stripe Configuration
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...

# Email Configuration (for verification and password reset)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
SMTP_FROM=your-email@gmail.com
FRONTEND_URL=http://localhost:3000
APP_NAME=FaceML
APP_URL=http://localhost:3000

# JWT Configuration (if not already set)
JWT_SECRET=your-secret-key
JWT_EXPIRES_IN=7d
```

## 📊 Database Tables Required

The following tables should exist in your database:

1. **subscription_plans** - Subscription plan definitions
   - id, name, price, duration_type, max_locations, max_staff, description, status, stripe_price_id, stripe_product_id, is_deleted

2. **user_subscriptions** - User subscription records
   - id, user_id, subscription_plan_id, plan_type, amount, start_date, end_date, status, payment_intent_id, stripe_subscription_id, stripe_customer_id, stripe_price_id, created_at, updated_at

3. **transactions** - Payment transaction records
   - id, user_id, amount, order_id, currency, status, plan_type, created_at, updated_at

4. **users** - Updated with new fields:
   - email_verified (TINYINT)
   - verification_token (VARCHAR)
   - verification_token_expiry (DATETIME)
   - password_reset_token (VARCHAR)
   - password_reset_token_expiry (DATETIME)
   - token (VARCHAR) - for access token storage
   - expires_at (BIGINT) - token expiry timestamp
   - first_name, last_name, shop_name, location (if not already present)

5. **user_notification_settings** - User notification preferences
   - id, user_id, account_notification, new_contest, contest_result, new_participation, voting_notification

## 🚀 Next Steps

1. **Install Dependencies:**
   ```bash
   cd backend
   npm install
   ```

2. **Update Environment Variables:**
   - Add Stripe keys
   - Add SMTP configuration for emails
   - Update frontend URL

3. **Database Migration:**
   - Run SQL scripts to create/update required tables
   - Ensure all new columns are added to existing tables

4. **Test the Integration:**
   - Test login with subscription checking
   - Test email verification flow
   - Test password reset flow
   - Test subscription creation and management

## 📝 Notes

- All subscription controllers use the database compatibility layer (`services/db.js`) to work with the existing mysql2/promise pool
- The middleware supports both `access_token` header (new) and `Authorization: Bearer` (old) for backward compatibility
- Email verification and password reset require SMTP configuration
- Stripe webhook requires proper signature verification setup



