import { Controller, Delete, Get, Post, Put } from '@overnightjs/core';
import { Request, Response } from 'express';
import DoctorService from '../services/DoctorService';

@Controller('api/doctors')
export class DoctorController {
  @Get()
  async getAllDoctors(req: Request, res: Response): Promise<void> {
    try {
      const limit = req.query.limit ? parseInt(req.query.limit as string) : 10;
      const page = req.query.page ? parseInt(req.query.page as string) : 1;
      const search = req.query.search ? String(req.query.search) : '';

      const result = await DoctorService.getAllDoctors(limit, page, undefined, search);
      res.json({ success: true, ...result });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  @Get(':id')
  async getDoctorById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const doctor = await DoctorService.getDoctorById(id);
      if (!doctor) {
        res.status(404).json({ success: false, error: 'Doctor not found' });
        return;
      }
      res.json({ success: true, data: doctor });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }

  @Post()
  async createDoctor(req: Request, res: Response): Promise<void> {
    try {
      const result = await DoctorService.createDoctorWithUser(req.body);
      res.status(201).json({
        success: true,
        data: result.doctor,
        message: result.message
      });
    } catch (error: any) {
      console.error('Create doctor error:', error);
      const statusCode = error.message.includes('already exists') ? 400 : 400;
      res.status(statusCode).json({ success: false, error: error.message });
    }
  }

  @Put(':id')
  async updateDoctor(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const doctor = await DoctorService.updateDoctor(id, req.body);
      if (!doctor) {
        res.status(404).json({ success: false, error: 'Doctor not found' });
        return;
      }
      res.json({ success: true, data: doctor });
    } catch (error: any) {
      res.status(400).json({ success: false, error: error.message });
    }
  }

  @Delete(':id')
  async deleteDoctor(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const doctor = await DoctorService.deleteDoctor(id);
      if (!doctor) {
        res.status(404).json({ success: false, error: 'Doctor not found' });
        return;
      }
      res.json({ success: true, message: 'Doctor deleted successfully' });
    } catch (error: any) {
      res.status(500).json({ success: false, error: error.message });
    }
  }
}

export default new DoctorController();
