import Prescription, { IPrescription } from '../models/Prescription';

export class PrescriptionService {
    async getAll(): Promise<IPrescription[]> {
        return await Prescription.find()
            .populate('patientId')
            .populate({ path: 'doctorId', populate: { path: 'userId', select: 'firstName lastName' } });
    }

    async getByPatientId(patientId: string): Promise<IPrescription[]> {
        return await Prescription.find({ patientId })
            .sort({ createdAt: -1 })
            .populate({ path: 'doctorId', populate: { path: 'userId', select: 'firstName lastName profileImage clinic' } });
    }

    async getById(id: string): Promise<IPrescription | null> {
        return await Prescription.findById(id)
            .populate('patientId')
            .populate({ path: 'doctorId', populate: { path: 'userId', select: 'firstName lastName profileImage clinic' } });
    }

    async create(data: Partial<IPrescription>): Promise<IPrescription> {
        const prescription = new Prescription(data);
        return await prescription.save();
    }

    async update(id: string, data: Partial<IPrescription>): Promise<IPrescription | null> {
        return await Prescription.findByIdAndUpdate(id, data, { new: true })
            .populate('patientId')
            .populate({ path: 'doctorId', populate: { path: 'userId', select: 'firstName lastName' } });
    }
}

export default new PrescriptionService();
