# Payment Integration Guide - Course Purchase Module

## Overview
The course purchase module integrates with Razorpay payment gateway using existing code located at `/razorpayment-gateway/razorpay-payment-gateway.js`. This guide explains the payment flow and API usage.

## Payment Flow

### 1. Initiate Purchase
```
POST /api/v1/coursePurchase/initiate
```

**Step 1**: User initiates a course purchase
- Creates `CoursePurchase` record with status `PENDING`
- Validates user profile completion, suspension status, course availability
- Returns `purchaseId`, `orderId`, and pricing details

**Response**:
```json
{
  "statusCode": 201,
  "message": "Course purchase initiated successfully",
  "data": {
    "purchase": {
      "purchaseId": 1,
      "orderId": "ORD-1234567890",
      "invoiceNumber": "INV-1234567890",
      "courseId": 5,
      "amount": 5000,
      "taxAmount": 900,
      "discountAmount": 0,
      "totalAmount": 5900,
      "currency": "INR",
      "purchaseStatus": "PENDING"
    }
  }
}
```

---

### 2. Initialize Payment
```
POST /api/v1/coursePurchase/:purchaseId/initialize-payment
```

**Step 2**: Frontend calls this endpoint to get Razorpay order details
- Creates Razorpay order using existing `createRazorpayOrder()` function
- Stores Razorpay `gatewayOrderId` in purchase record
- Returns Razorpay order ID and key ID for frontend widget

**Uses Existing Function**:
```javascript
import { createRazorpayOrder, createRazorpayInstance } 
  from '../../../razorpayment-gateway/razorpay-payment-gateway.js';

const razorpayInstance = createRazorpayInstance();
const orderResponse = await createRazorpayOrder({
  amount: 5900,
  currency: 'INR',
  receipt: 'ORD-1234567890',
  description: 'Course Purchase - ORD-1234567890',
  notes: { purchaseId: 1, courseId: 5, userId: 10 }
}, razorpayInstance);
```

**Response**:
```json
{
  "statusCode": 200,
  "message": "Payment order created. Ready for payment.",
  "data": {
    "payment": {
      "purchaseId": 1,
      "orderId": "ORD-1234567890",
      "razorpayOrderId": "order_K7ZH4Z",
      "amount": 5900,
      "currency": "INR",
      "keyId": "rzp_live_xxxxx"
    }
  }
}
```

---

### 3. Payment on Frontend
**Step 3**: Frontend opens Razorpay payment widget

```javascript
// Frontend code (React example)
const handlePayment = (paymentData) => {
  const options = {
    key: paymentData.keyId,
    amount: paymentData.amount * 100,
    currency: paymentData.currency,
    order_id: paymentData.razorpayOrderId,
    handler: (response) => {
      // Call verify endpoint
      verifyPayment(response);
    },
    prefill: {
      email: userEmail,
      contact: userPhone,
      name: userName
    }
  };
  
  const rzp = new window.Razorpay(options);
  rzp.open();
};
```

**User completes payment in Razorpay widget**
- User enters card/payment details
- Razorpay processes payment
- On success, returns `paymentId`, `orderId`, `signature`

---

### 4. Verify Payment
```
POST /api/v1/coursePurchase/verify-payment
```

**Step 4**: Frontend sends verification request with payment details
- Verifies Razorpay signature using existing `verifyRazorpaySignature()` function
- Updates purchase status to `SUCCESS`
- Stores payment details in database
- Sends success email to user

**Uses Existing Functions**:
```javascript
import { verifyRazorpaySignature, handlePaymentStatus } 
  from '../../../razorpayment-gateway/razorpay-payment-gateway.js';
import { sendCoursePaymentSuccessEmail } 
  from '../../../smtp/emailService.js';

// Verify signature
verifyRazorpaySignature(orderId, paymentId, signature, RAZORPAY_KEY_SECRET);

// Update database
await purchase.update({
  purchaseStatus: 'SUCCESS',
  gatewayPaymentId: paymentId,
  gatewaySignature: signature,
  paymentDate: new Date()
});

// Send email
await sendCoursePaymentSuccessEmail(
  user.emailId,
  userName,
  courseName,
  purchaseDate,
  accessPeriod,
  instructorName,
  courseLink
);
```

**Request Body**:
```json
{
  "purchaseId": 1,
  "paymentId": "pay_K7ZH4Z",
  "orderId": "order_K7ZH4Z",
  "signature": "ab4c2d4b4f4b4d4e4f4g4h4i4j4k4l4"
}
```

**Response**:
```json
{
  "statusCode": 200,
  "message": "✅ Payment successful! Confirmation email sent to your registered email address.",
  "data": {
    "purchase": {
      "purchaseId": 1,
      "orderId": "ORD-1234567890",
      "paymentId": "pay_K7ZH4Z",
      "paymentStatus": "SUCCESS",
      "amount": 5900,
      "currency": "INR",
      "user": {
        "id": 10,
        "name": "John Doe",
        "email": "john@example.com"
      },
      "course": {
        "id": 5,
        "courseName": "Python Basics",
        "courseCode": "PYTHON-101"
      }
    }
  }
}
```

---

## Webhook Processing

### Razorpay Webhook Events
```
POST /api/v1/coursePurchase/webhook
Headers: X-Razorpay-Signature (required)
```

**Webhook Events Handled**:

1. **payment.authorized** / **payment.captured**
   - Updates purchase status to `SUCCESS`
   - Sends success email
   - Grants course access

2. **payment.failed**
   - Updates purchase status to `FAILED`
   - No email sent
   - User can retry

3. **refund.created**
   - Updates purchase status to `REFUNDED`
   - Stores refund amount and date

**Webhook Verification** (uses existing function):
```javascript
import { verifyWebhookSignature, handlePaymentStatus } 
  from '../../../razorpayment-gateway/razorpay-payment-gateway.js';

// Verify webhook signature
verifyWebhookSignature(webhookBody, webhookSignature, RAZORPAY_KEY_SECRET);

// Handle payment status
const paymentStatus = handlePaymentStatus(eventName, payload);
```

---

## Refund Processing

### Request Refund
```
POST /api/v1/coursePurchase/:purchaseId/refund
```

**Uses Existing Function**:
```javascript
import { refundPayment, createRazorpayInstance } 
  from '../../../razorpayment-gateway/razorpay-payment-gateway.js';

const razorpayInstance = createRazorpayInstance();
const refundResult = await refundPayment(
  paymentId,
  { amount: 5900, reason: 'Refund requested by user' },
  razorpayInstance
);
```

**Request Body**:
```json
{
  "amount": 5900,
  "reason": "User requested refund"
}
```

**Response**:
```json
{
  "statusCode": 200,
  "message": "Refund processed successfully",
  "data": {
    "refund": {
      "purchaseId": 1,
      "refundId": "rfnd_K7ZH4Z",
      "amount": 5900,
      "status": "REFUNDED"
    }
  }
}
```

---

## Database Records

### CoursePurchase Table

| Field | Type | Description |
|-------|------|-------------|
| purchaseId | INT PK | Unique purchase ID |
| userId | INT FK | User making purchase |
| courseId | INT FK | Course being purchased |
| orderId | VARCHAR | System order ID (ORD-xxx) |
| invoiceNumber | VARCHAR | Unique invoice number |
| amount | DECIMAL | Course base price |
| taxAmount | DECIMAL | Tax calculated |
| discountAmount | DECIMAL | Discount applied |
| totalAmount | DECIMAL | Final amount paid |
| currency | VARCHAR | Currency (INR) |
| purchaseStatus | ENUM | PENDING/SUCCESS/FAILED/REFUNDED |
| paymentGateway | VARCHAR | Gateway used (razorpay) |
| gatewayOrderId | VARCHAR | Razorpay order ID |
| gatewayPaymentId | VARCHAR | Razorpay payment ID |
| gatewaySignature | VARCHAR | Payment signature |
| paymentDate | DATETIME | Payment completion time |
| refundAmount | DECIMAL | Refunded amount |
| refundReason | TEXT | Refund reason |
| refundDate | DATETIME | Refund completion time |
| createdAt | DATETIME | Record creation |
| updatedAt | DATETIME | Record update |

---

## Configuration

### Environment Variables Required

```env
# Razorpay
RAZORPAY_KEY_ID=rzp_live_xxxxx        # Your Razorpay key ID
RAZORPAY_KEY_SECRET=xxxxxxxxxxxxxxxx  # Your Razorpay key secret

# Frontend
FRONTEND_URL=https://app.buddymentor.com  # For email links

# SMTP (for success emails)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=noreply@buddymentor.com
SMTP_PASS=xxxxxxxxxxxxx
```

---

## Error Handling

### Common Errors

**Signature Verification Failed**
```json
{
  "statusCode": 401,
  "message": "Signature verification failed - Possible tampering detected",
  "error": true
}
```

**Purchase Not Found**
```json
{
  "statusCode": 404,
  "message": "Purchase not found",
  "error": true
}
```

**Already Purchased**
```json
{
  "statusCode": 400,
  "message": "User has already purchased this course",
  "error": true
}
```

**Profile Incomplete**
```json
{
  "statusCode": 400,
  "message": "User profile is incomplete",
  "error": true,
  "missingFields": ["email_verified", "firstName", "lastName"]
}
```

---

## Integration Points

### Existing Razorpay Code
Location: `/razorpayment-gateway/razorpay-payment-gateway.js`

**Exported Functions Used**:
- `createRazorpayInstance()` - Initialize Razorpay SDK
- `createRazorpayOrder(params, razorpayInstance)` - Create order
- `verifyRazorpaySignature(orderId, paymentId, signature, keySecret)` - Verify signature
- `refundPayment(paymentId, params, razorpayInstance)` - Process refund
- `verifyWebhookSignature(body, signature, keySecret)` - Verify webhook
- `handlePaymentStatus(eventName, payload)` - Handle webhook events

### Email Service
Location: `/smtp/emailService.js`

**Function Used**:
- `sendCoursePaymentSuccessEmail(email, userName, courseName, purchaseDate, accessPeriod, instructorName, courseLink)`

---

## Testing

### Manual Testing Steps

1. **Initiate Purchase**
   ```bash
   curl -X POST http://localhost:3000/api/v1/coursePurchase/initiate \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{ "courseId": 5 }'
   ```

2. **Initialize Payment**
   ```bash
   curl -X POST http://localhost:3000/api/v1/coursePurchase/1/initialize-payment \
     -H "Authorization: Bearer YOUR_TOKEN"
   ```

3. **Verify Payment** (After manual payment in Razorpay dashboard)
   ```bash
   curl -X POST http://localhost:3000/api/v1/coursePurchase/verify-payment \
     -H "Authorization: Bearer YOUR_TOKEN" \
     -H "Content-Type: application/json" \
     -d '{
       "purchaseId": 1,
       "paymentId": "pay_xxxxx",
       "orderId": "order_xxxxx",
       "signature": "signature_xxxxx"
     }'
   ```

### Test Credentials (Razorpay Sandbox)
- Key ID: Available in Razorpay dashboard
- Test Card: 4111 1111 1111 1111
- Expiry: Any future date
- CVV: Any 3 digits

---

## Notes

- All payment functions use existing code from `/razorpayment-gateway/`
- Email templates are located in `/smtp/templates/`
- Database migrations for `CoursePurchase` table already executed
- Webhook signature verification prevents tampering
- Payment status updates are idempotent (safe to retry)
