# SMS Notifications Usage Guide

This guide shows how to use the SMS notification system in your application. All SMS messages are automatically logged to the `sms_logs` database table.

## Import

```javascript
import { Notification } from "../notifications/index.js";
// or based on your location:
import { Notification } from "../../../notifications/index.js";
```

---

## 1. Send OTP (One-Time Password)

**Use Case:** User registration, login verification, password reset

```javascript
try {
  await Notification.sms.sendOTP({
    mobile: "9876543210",
    otp: "123456",
    validity: 10, // optional, minutes (default: 10)
  });
  console.log("OTP sent successfully");
} catch (error) {
  console.error("Failed to send OTP:", error.message);
}
```

---

## 2. Send Registration Discount

**Use Case:** Welcome offer after user registration

```javascript
await Notification.sms.sendRegistrationDiscount({
  mobile: "9876543210",
  discount: "20", // discount percentage
  coupon: "BUDDY20", // coupon code
});
```

---

## 3. Send Week Starting Notification

**Use Case:** Alert users when their weekly course starts

```javascript
await Notification.sms.sendWeekStarting({
  mobile: "9876543210",
});
```

---

## 4. Send Weekly Failure Alert

**Use Case:** Notify user when they miss weekly targets

```javascript
await Notification.sms.sendWeeklyFailure({
  mobile: "9876543210",
  plan: "JavaScript Basics", // course/plan name
});
```

---

## 5. Send Weekly Success Alert

**Use Case:** Congratulate user on completing weekly objectives

```javascript
await Notification.sms.sendWeeklySuccess({
  mobile: "9876543210",
  code: "WEEK1_COMPLETE", // achievement code
});
```

---

## 6. Send Content Revision Alert

**Use Case:** Notify about updated course content

```javascript
await Notification.sms.sendContentRevision({
  mobile: "9876543210",
  code: "PYTHON_ADV_v2", // content code
});
```

---

## 7. Send Payment Confirmation

**Use Case:** Confirm payment and order details

```javascript
await Notification.sms.sendPaymentConfirmation({
  mobile: "9876543210",
  price: "299", // amount paid
  code: "ORDER_12345", // order reference
});
```

---

## Real-World Examples

### Example 1: During User Registration

```javascript
// In src/modules/users/userAuth/auth.service.js

import { Notification } from "../../../notifications/index.js";

export const registerUser = async (userData) => {
  // Create user in database
  const newUser = await db.AuthUser.create({
    emailId: userData.email,
    mobile: userData.mobile,
    // ... other fields
  });

  // Generate OTP
  const otp = Math.floor(100000 + Math.random() * 900000).toString();

  // Send OTP SMS (automatically logged)
  try {
    await Notification.sms.sendOTP({
      mobile: userData.mobile,
      otp: otp,
      validity: 15,
    });
  } catch (error) {
    console.error("Could not send OTP:", error.message);
    // Error is logged in database with FAILED status
  }

  // Send welcome discount after OTP verification
  await Notification.sms.sendRegistrationDiscount({
    mobile: userData.mobile,
    discount: "25",
    coupon: "WELCOME25",
  });

  return newUser;
};
```

### Example 2: After Course Purchase

```javascript
// In src/modules/users/coursePurchase/purchase.service.js

import { Notification } from "../../../notifications/index.js";

export const completePurchase = async (purchaseData) => {
  // Create purchase record
  const purchase = await db.CoursePurchase.create(purchaseData);

  // Send payment confirmation
  await Notification.sms.sendPaymentConfirmation({
    mobile: purchaseData.userMobile,
    price: purchaseData.amount,
    code: purchase.orderId,
  });

  return purchase;
};
```

### Example 3: In Cron Job for Weekly Notifications

```javascript
// In src/cron/weeklyCron.js

import { Notification } from "../notifications/index.js";

export const sendWeeklyNotifications = async () => {
  // Get all active enrollments
  const enrollments = await db.UserCourseEnrollment.findAll({
    where: { status: "ACTIVE" },
  });

  for (const enrollment of enrollments) {
    const user = await enrollment.getAuthUser();

    // Check if week started
    if (isWeekStarting(enrollment)) {
      await Notification.sms.sendWeekStarting({
        mobile: user.mobile,
      });
    }

    // Check if targets met
    const weekProgress = await getWeekProgress(enrollment.id);

    if (weekProgress.completed) {
      await Notification.sms.sendWeeklySuccess({
        mobile: user.mobile,
        code: `WEEK${enrollment.weekNumber}_COMPLETE`,
      });
    } else if (weekProgress.missed) {
      await Notification.sms.sendWeeklyFailure({
        mobile: user.mobile,
        plan: enrollment.courseName,
      });
    }
  }
};
```

---

## Checking SMS Logs in Database

### Query all SMS logs

```javascript
import { db } from "../../database/models/index.js";

const allLogs = await db.SmsLog.findAll();
```

### Get SMS for specific mobile

```javascript
const userLogs = await db.SmsLog.findAll({
  where: { mobile: "9876543210" },
  order: [["sentAt", "DESC"]],
});
```

### Get failed SMS (for debugging)

```javascript
const failedSMS = await db.SmsLog.findAll({
  where: { status: "FAILED" },
});
```

### Get SMS by template type

```javascript
const otpLogs = await db.SmsLog.findAll({
  where: { templateKey: "OTP" },
});
```

### Get SMS sent in last 24 hours

```javascript
import { Op } from "sequelize";

const recentSMS = await db.SmsLog.findAll({
  where: {
    sentAt: {
      [Op.gte]: new Date(Date.now() - 24 * 60 * 60 * 1000),
    },
  },
  order: [["sentAt", "DESC"]],
});
```

---

## SMS Log Fields

Each SMS creates a database record with:

| Field | Type | Description |
|-------|------|-------------|
| id | BIGINT | Unique identifier |
| mobile | STRING | Recipient mobile number |
| templateKey | STRING | SMS template type (OTP, WEEK_STARTING, etc.) |
| templateId | STRING | MSG91 template ID |
| variables | JSON | Template variables sent |
| status | ENUM | PENDING, SENT, DELIVERED, FAILED, INVALID_MOBILE |
| response | JSON | MSG91 API response or error details |
| sentAt | DATE | When SMS was sent |
| createdAt | DATE | Record creation time |
| updatedAt | DATE | Last update time |

---

## Error Handling

All SMS functions support try-catch:

```javascript
try {
  await Notification.sms.sendOTP({
    mobile: "9876543210",
    otp: "123456",
  });
} catch (error) {
  // Error logged in sms_logs table with FAILED status
  console.error("SMS Error:", error.message);
  
  // You can still access the log entry to see what went wrong
  const failedLog = await db.SmsLog.findOne({
    where: { mobile: "9876543210", status: "FAILED" },
    order: [["createdAt", "DESC"]],
  });
  console.log("Error details:", failedLog.response);
}
```

---

## Environment Setup

Make sure these are in your `.env` file:

```env
MSG91_AUTH_KEY=your_msg91_auth_key
MSG91_SENDER_ID=BUDMEN
MSG91_ROUTE=4
```

---

## Supported SMS Functions

| Function | Parameters | Use Case |
|----------|-----------|----------|
| `sendOTP` | mobile, otp, validity | OTP verification |
| `sendRegistrationDiscount` | mobile, discount, coupon | Welcome offer |
| `sendWeekStarting` | mobile | Week start notification |
| `sendWeeklyFailure` | mobile, plan | Weekly miss alert |
| `sendWeeklySuccess` | mobile, code | Weekly success alert |
| `sendContentRevision` | mobile, code | Content update notification |
| `sendPaymentConfirmation` | mobile, price, code | Payment confirmation |
