# AI Development Instructions - Server

Follow these instructions strictly before and during development of the Medklinix Platform backend.

## Before Starting Development, ALWAYS:

1. **Read entire AI instructions code** 
   - Understand all guidelines before implementation
   - Review this file completely before writing any code

2. **Read README file entirely** 
   - Don't start generating code before understanding the full scope
   - Review [README.md](README.md) to understand project requirements
   - Understand all modules and deliverables

3. **Understand backend architecture** 
   - Know the API structure and database schema before generating code
   - Review existing controllers, services, and models
   - Understand the MVC pattern being used
   - Check [ARCHITECTURE.md](ARCHITECTURE.md) and [ADDING_ROUTES.md](ADDING_ROUTES.md)

4. **Know the file structure** 
   - Understand the project structure before generating code
   - Review existing folder hierarchy: [src/](src/)
   - Keep new files organized following existing patterns
   - Maintain separation of concerns (Controllers, Services, Models)

5. **Use existing code only** 
   - Don't generate new code until user explicitly asks
   - Reuse and extend existing code whenever possible
   - Leverage existing services and utilities
   - Build incrementally on what's already there

6. **Maintain reusable services** 
   - Avoid duplicate code
   - Create reusable service layers
   - Extract common functionality into shared utilities
   - Document service methods and usage
   - Follow DRY (Don't Repeat Yourself) principle

7. **API must be efficient** 
   - Clean and optimized API design to support 1M+ concurrent users
   - Implement proper caching strategies
   - Optimize database queries
   - Use pagination for large datasets
   - Implement rate limiting and throttling
   - Monitor and optimize performance

8. **Must follow requirements** 
   - Strictly adhere to all project requirements
   - Refer to README.md for main modules:
     - Patient Record API
     - Individual Patient Page endpoints
     - Appointment Calendar API
     - Medical/Dental Record API with odontogram support
     - Prescription Forms API with signature support
     - Search Engine API
     - Payment Gateway integration (PayPal, Stripe)
   - Implement role-based access control (Doctor, Assistant, Admin)
   - Ensure data encryption at rest and in transit

---

## Interface Requirements

**All server APIs and features MUST adhere to these interface requirements:**

- Clear and fast API responses optimized for all devices
- Responsive backend design supporting mobile, tablet, and desktop clients
- Professional API standards to support 1M+ concurrent users
- Fast response times (< 200ms for typical queries)
- Accessibility compliance for API documentation
- Consistent API interface across all endpoints

---

## Expected Deliverables

**Developers MUST ensure these deliverables are completed:**

1. Complete source code (frontend and backend) with deployment instructions
2. Structured database and installation script
3. Brief user manual in Spanish
4. Online demo for functional testing
5. Deployment online ready for launch

---

## Key Requirements for Server Development

### Technology Stack
- **Runtime**: Node.js 18+
- **Language**: TypeScript
- **Framework**: Express.js
- **Database**: MongoDB
- **HTTP Client**: Axios for external API calls
- **Package Manager**: npm

### Project Structure
```
src/
├── index.ts                    (Entry point)
├── controllers/                (Request handlers)
│   ├── PatientController.ts
│   ├── AppointmentController.ts
│   ├── DoctorController.ts
│   └── index.ts
├── services/                   (Business logic)
│   ├── PatientService.ts
│   ├── AppointmentService.ts
│   ├── DoctorService.ts
│   └── index.ts
├── models/                     (Database schemas)
│   ├── Patient.ts
│   ├── Appointment.ts
│   ├── Doctor.ts
│   └── index.ts
├── middleware/                 (Auth, validation, errors)
├── utils/                      (Helper functions)
├── config/                     (Configuration files)
└── routes/                     (API route definitions)
```

### MVC Architecture Pattern
- **Models**: Define MongoDB schemas and interfaces
- **Controllers**: Handle HTTP requests and responses
- **Services**: Contain business logic and data processing
- **Routes**: Define API endpoints
- **Middleware**: Handle authentication, validation, error handling

### API Design Guidelines
1. Use RESTful conventions
2. Return consistent JSON responses
3. Include proper HTTP status codes
4. Implement proper error handling
5. Add request validation
6. Use pagination for list endpoints
7. Document all endpoints

### Database Considerations
- Use MongoDB with Mongoose
- Create indexes on frequently queried fields
- Implement soft deletes for important data
- Use transactions for multi-document operations
- Encrypt sensitive data (passwords, medical records, etc.)
- Implement data backup strategies

### Security Requirements
- Implement JWT authentication
- Hash passwords using bcrypt
- Validate all user inputs
- Implement CORS properly
- Add rate limiting
- Encrypt sensitive data in database
- Use HTTPS in production
- Implement role-based access control (RBAC)

### Performance Optimization
- Cache frequently accessed data
- Use lean() for Mongoose queries when full documents not needed
- Implement pagination for large datasets
- Use select() to limit fields returned
- Monitor and optimize database queries
- Implement connection pooling

### Development Workflow
1. Check existing code before writing new code
2. Review existing services and controllers
3. Create or extend services for new features
4. Create controllers that use those services
5. Add proper error handling and validation
6. Test APIs thoroughly
7. Document new endpoints

### Important Notes
- All routes must follow existing patterns
- Implement proper error handling globally
- Use TypeScript for type safety
- Follow async/await patterns
- Keep services focused on single responsibility
- Document complex business logic
- Support both development and Vercel deployment

---

## API Response Format

All endpoints should follow this response structure:

```typescript
// Success response
{
  success: true,
  data: { /* response data */ },
  message: "Operation completed successfully"
}

// Error response
{
  success: false,
  error: "Error message",
  statusCode: 400
}
```

---

## Checklist Before Submitting Code

- [ ] Read entire README.md
- [ ] Read ARCHITECTURE.md and ADDING_ROUTES.md
- [ ] Read all AI instructions
- [ ] Understood existing backend structure
- [ ] Used existing services and patterns
- [ ] No duplicate code maintained
- [ ] Proper error handling implemented
- [ ] Followed all project requirements
- [ ] Code is well-commented
- [ ] API responses follow standard format
- [ ] Database queries are optimized
- [ ] Security best practices followed
- [ ] Ready for 1M+ concurrent users
- [ ] TypeScript strict mode compliance
