import { Controller, Get, Middleware, Post, Put } from '@overnightjs/core';
import { Request, Response } from 'express';
import { auth, AuthRequest } from '../middleware/auth';
import PatientService from '../services/PatientService';
import PrescriptionService from '../services/PrescriptionService';

@Controller('api/prescriptions')
export class PrescriptionController {

    @Get('patient/:patientId')
    @Middleware(auth)
    async getByPatientId(req: Request, res: Response): Promise<void> {
        try {
            const { patientId } = req.params;
            const prescriptions = await PrescriptionService.getByPatientId(patientId);
            res.json({ success: true, data: prescriptions });
        } catch (error: any) {
            res.status(500).json({ success: false, error: error.message });
        }
    }

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

    @Post()
    @Middleware(auth)
    async create(req: Request, res: Response): Promise<void> {
        try {
            const userId = (req as AuthRequest).user.userId;
            let { doctorId } = req.body;

            // Auto-resolve doctorId from authenticated user if not provided
            if (!doctorId) {
                doctorId = await PatientService.getDoctorIdFromUserId(userId);
            }

            const prescription = await PrescriptionService.create({
                ...req.body,
                doctorId
            });
            res.status(201).json({ success: true, data: prescription });
        } catch (error: any) {
            res.status(400).json({ success: false, error: error.message });
        }
    }

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