# 📧 SendGrid Email Configuration

## Environment Variables

Add these variables to your `.env` file:

```env
# ============================================================
# EMAIL CONFIGURATION (SendGrid)
# ============================================================

# Email Provider (use 'sendgrid' for SendGrid, 'smtp' for SMTP)
EMAIL_PROVIDER=sendgrid

# SendGrid Configuration (REQUIRED for password reset emails)
SEND_GRID_API=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
FROM_EMAIL=praveen.jogi@apexneural.com
FROM_NAME=Apex Neural

# Frontend URLs (REQUIRED for password reset links)
FRONTEND_RESET_URL=https://dbaas.apexneural.cloud/reset-password
FRONTEND_BASE_URL=https://dbaas.apexneural.cloud

# ============================================================
# ALTERNATIVE: SMTP CONFIGURATION (if not using SendGrid)
# ============================================================

# SMTP Settings (optional - only if EMAIL_PROVIDER=smtp)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your-email@gmail.com
SMTP_PASSWORD=your-app-password
SMTP_FROM_EMAIL=noreply@yourapp.com
SMTP_USE_TLS=true
```

## Setup Steps

### 1. Install SendGrid Package

```bash
pip install sendgrid>=6.11.0
```

Or if using the package in editable mode:

```bash
pip install -e .
```

### 2. Verify SendGrid Sender

In your SendGrid account:
1. Go to **Settings** → **Sender Authentication**
2. Verify the email address: `praveen.jogi@apexneural.com`
3. This is required before you can send emails

### 3. Create SendGrid API Key

1. Go to **Settings** → **API Keys**
2. Click **Create API Key**
3. Name it (e.g., "Apex Backend Production")
4. Select **Full Access** or **Restricted Access** with:
   - Mail Send: **Full Access**
5. Copy the API key and add it to your `.env` file as `SEND_GRID_API`

### 4. Test Email Sending

You can test the email functionality by calling the forgot password endpoint:

```bash
curl -X POST http://localhost:8000/api/v1/auth/forgot-password \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com"}'
```

## Password Reset Flow

### User Requests Password Reset

**Endpoint:** `POST /api/v1/auth/forgot-password`

**Request:**
```json
{
  "email": "user@example.com"
}
```

**Response:**
```json
{
  "message": "If the email exists, a password reset link has been sent",
  "success": true
}
```

**What Happens:**
1. System finds user by email
2. Generates secure reset token (valid for 1 hour)
3. Stores token in database
4. Sends email via SendGrid with reset link:
   - Link format: `https://dbaas.apexneural.cloud/reset-password?token=ABC123...`
   - Email sent from: `praveen.jogi@apexneural.com`

### User Resets Password

**Endpoint:** `POST /api/v1/auth/reset-password`

**Request:**
```json
{
  "token": "ABC123...",
  "new_password": "MyNewPassword123"
}
```

**Response (Success):**
```json
{
  "message": "Password has been reset successfully. You can now login with your new password.",
  "success": true
}
```

**Response (Failure):**
```json
{
  "detail": "Invalid or expired reset token. Please request a new password reset."
}
```

## Email Template

The password reset email uses a professional HTML template with:
- User's name personalization
- Clickable "Reset Password" button
- Plain text link as fallback
- 1-hour expiration notice
- Security notice (if you didn't request this, ignore it)

You can customize the template in:
`src/apex/infrastructure/email/templates.py`

## Using SendGrid Dynamic Templates (Optional)

If you want to use SendGrid's dynamic templates instead of the built-in HTML templates:

```python
from apex.infrastructure.email.sendgrid import SendGridEmailAdapter

# Initialize adapter
sendgrid = SendGridEmailAdapter()

# Send using SendGrid template
await sendgrid.send_template_email(
    to="user@example.com",
    template_id="d-1234567890abcdef",  # Your template ID from SendGrid
    dynamic_data={
        "user_name": "John Doe",
        "reset_link": "https://dbaas.apexneural.cloud/reset-password?token=ABC123",
        "expiry_hours": 1,
    }
)
```

## Troubleshooting

### Email Not Sending

1. **Check API Key:** Ensure `SEND_GRID_API` is correct in `.env`
2. **Verify Sender:** Make sure `FROM_EMAIL` is verified in SendGrid
3. **Check Logs:** Look for error messages in console output
4. **Test Connection:** Use SendGrid's API test endpoint

### Email Going to Spam

1. Verify sender authentication (SPF, DKIM)
2. Add your domain to SendGrid's sender authentication
3. Use a custom domain instead of Gmail/Yahoo addresses

### Token Expired

- Reset tokens expire after 1 hour
- User needs to request a new password reset
- Check `reset_token_expires` field in database

## Security Features

✅ **Token Security:**
- Cryptographically random (32 bytes)
- Single-use (cleared after successful reset)
- Time-limited (1 hour expiration)

✅ **Email Enumeration Prevention:**
- Always returns success, even if email doesn't exist
- Prevents attackers from discovering valid emails

✅ **Password Requirements:**
- Minimum 8 characters (enforced by Pydantic)
- Hashed with bcrypt before storage

## Production Checklist

- [ ] SendGrid sender email verified
- [ ] API key created with Mail Send permissions
- [ ] Environment variables configured in `.env`
- [ ] Frontend reset URL matches your domain
- [ ] Email template customized (optional)
- [ ] Test password reset flow end-to-end
- [ ] Set up monitoring for failed email sends
- [ ] Configure rate limiting on forgot-password endpoint

