# Troubleshooting

### Common Issues and Solutions

#### 1. Database Connection Failed

**Error:**
```
Unable to connect Osas database: SequelizeConnectionError
```

**Solutions:**
- Check PostgreSQL is running: `systemctl status postgresql`
- Verify database credentials in `.env`
- Ensure database exists: `psql -U postgres -l`
- Check network connectivity to database server
- Verify firewall allows PostgreSQL port (5432)

#### 2. JWT Token Invalid

**Error:**
```
{
  "message": "Unauthorized",
  "error": "Invalid token"
}
```

**Solutions:**
- Verify JWT_SECRET in `.env` matches token generation
- Check token expiration (JWT_EXPIRATION setting)
- Ensure Authorization header format: `Bearer <token>`
- Generate new token via `/api/auth/signin`

#### 3. Rate Limit Exceeded

**Error:**
```
{
  "message": "You are sending requests too quickly. Please wait 1 second."
}
```

**Solutions:**
- Wait for rate limit window to reset
- Adjust RATE_LIMIT_WINDOW_MS and RATE_LIMIT_MAX in `.env`
- Implement request queuing in client
- Use batch endpoints where available

#### 4. File Upload Failed

**Error:**
```
{
  "message": "File too large"
}
```

**Solutions:**
- Check file size < 10MB
- Verify `resources/temp/img/` directories exist
- Check disk space: `df -h`
- Ensure correct multipart/form-data encoding

#### 5. Courier Webhook Not Working

**Error:**
Webhooks not updating status

**Solutions:**
- Verify courier credentials in `.env`
- Check webhook endpoint is accessible (not localhost)
- Validate webhook authentication (Basic Auth, API Key)
- Check courier status mapping in `app/status/`
- Review webhook logs in console
- Test with webhook testing tools (ngrok, webhook.site)

#### 6. Fee Calculation Returns 0

**Error:**
```
{
  "fee": 0
}
```

**Solutions:**
- Verify origin/destination codes are valid
- Check location data in database
- Ensure service availability for route
- Review pricing configuration
- Check for special pricing rules
- Validate weight parameter

#### 7. Sequelize Migration Issues

**Error:**
```
SequelizeDatabaseError: relation does not exist
```

**Solutions:**
- Run migrations: Check for migration scripts
- Sync models: `db.sequelize.sync({ alter: true })`
- Check model definitions match database schema
- Verify table names in model files

#### 8. CORS Errors

**Error:**
```
Access to fetch blocked by CORS policy
```

**Solutions:**
- Add origin to ORIGIN_CORS environment variable
- Verify CORS configuration in `ondeliv-backend.js`
- Check request includes proper headers
- Ensure preflight OPTIONS requests are handled

#### 9. Image Not Loading

**Error:**
404 on image URLs

**Solutions:**
- Verify image directories exist:
  - `resources/temp/img/pickup/`
  - `resources/temp/img/delivery/`
  - `resources/temp/img/agent/`
- Check file permissions
- Verify image processing with Sharp
- Check BASEURL environment variable

#### 10. Cron Job Not Running

**Error:**
Lion Parcel pickup not scheduling

**Solutions:**
- Verify LIONPARCEL_PICKUP_CRON format is valid
- Check cron expression: `*/30 * * * *`
- Review cron job logs in console
- Ensure Lion Parcel credentials configured
- Test cron expression: https://crontab.guru

### Debug Mode

**Enable Verbose Logging:**

```javascript
// Add to ondeliv-backend.js temporarily
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  console.log('Headers:', req.headers);
  console.log('Body:', req.body);
  next();
});
```

**Database Query Logging:**

```javascript
// In db.config.js
module.exports = {
  // ... existing config
  logging: console.log,  // Enable SQL query logging
};
```

### Health Check Endpoint

**Check Server Status:**

```bash
curl http://localhost:4220/
```

**Expected Response:**
```json
{
  "message": "This backend osas works well for now"
}
```

### Performance Monitoring

**Check Database Connection:**

```javascript
// Test database connectivity
const testConnection = async () => {
  try {
    await db.sequelize.authenticate();
    console.log('Database connected');
  } catch (error) {
    console.error('Database connection failed:', error);
  }
};
```

**Monitor Response Times:**

Morgan logs include response time in cyan color.

### Getting Help

**Resources:**
- Review error logs in console
- Check courier partner documentation
- Review Sequelize documentation for database issues
- Check Express.js documentation for routing issues

**Contact:**
- Check repository issues
- Review pull request discussions
- Contact system administrator