import { connection } from "../configs/db.js";
import { verifyCookies } from "../auth/auth.js";
import express from "express";

const medicalReport = express.Router();

// Create report

medicalReport.post("/create", verifyCookies, async(req, res) => {
    try {
        if(req.role !== "doctor") return res.status(403).json({ message: "Forbidden" });

        const { appointmentId, diagnosis, perscription } = req.body;

        if(!appointmentId || !diagnosis || !perscription) return res.status(400).json({ message: "Appointment ID, diagnosis and perscription are required" });

        const sql = "SELECT * FROM medical_report WHERE appointment_id = ? AND doctor_id = ?";
        const [doesReportExist] = await connection.query(sql, [appointmentId, req.id]);
        if(doesReportExist.length > 0) return res.status(400).json({ message: "Report already exists" });

        const insertSQL = "INSERT INTO medical_report (appointment_id, doctor_id, diagnosis, perscription, report_date) VALUES (?, ?, ?, ?, ?)";
        const [insertResult] = await connection.query(insertSQL, [appointmentId, req.id, diagnosis, perscription, new Date()]);
        if(insertResult.affectedRows > 0) return res.status(201).json({ message: "Report created successfully" });
        return res.status(500).json({ message: "Failed to create report" });
    } catch (error) {
        console.error("Error creating report:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

// delete report

medicalReport.delete("/delete/:id", verifyCookies, async(req, res) => {
    try {
        const { id } = req.params;
        if(req.role !== "doctor") return res.status(403).json({ message: "Forbidden" });

        const sql = "DELETE FROM medical_report WHERE id = ?";

        const [deleteResult] = await connection.query(sql, [id]);
        if(deleteResult.affectedRows > 0){
            return res.status(200).json({ message: "Report deleted successfully" });
        }else{
            return res.status(404).json({ message: "Report not found" });
        }
    } catch (error) {
        console.error("Error deleting report:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

// update report

medicalReport.put("/update/:id", verifyCookies, async(req, res) => {
    try {
        const { id } = req.params;
        if(req.role !== "doctor") return res.status(403).json({ message: "Forbidden" });

        const { appointmentId, diagnosis, perscription } = req.body;
        if(!appointmentId || !diagnosis || !perscription) return res.status(400).json({ message: "Appointment ID, diagnosis and perscription are required" });

        const sql = "SELECT * FROM medical_report WHERE id = ? AND doctor_id = ?";
        const [doesReportExist] = await connection.query(sql, [id, req.id]);
        if(doesReportExist.length === 0) return res.status(400).json({ message: "Report does not exist" });

        const updateSQL = "UPDATE medical_report SET appointment_id = ?, diagnosis = ?, perscription = ?, report_date = ? WHERE id = ?";
        const [updateResult] = await connection.query(updateSQL, [appointmentId, diagnosis, perscription, new Date(), id]);
        if(updateResult.affectedRows > 0){
            return res.status(200).json({ message: "Report updated successfully" });
        }else{
            return res.status(404).json({ message: "Report not found" });
        }
    } catch (error) {
        console.error("Error updating report:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

// get reports all

medicalReport.get("/all", verifyCookies, async(req, res) => {
    try {
        const sql = "SELECT * FROM medical_report";
        const [results] = await connection.query(sql);

        if(results.length > 0){
            return res.status(200).json(results);
        }else{
            return res.status(204).json({ message: "No reports found" });
        }
    } catch (error) {
        console.error("Error fetching reports:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

// get report by id

medicalReport.get("/:id", verifyCookies, async(req, res) => {
    try {
        const { id } = req.params;
        const sql = "SELECT * FROM medical_report WHERE id = ?";
        const [results] = await connection.query(sql, [id]);

        if(results.length > 0){
            return res.status(200).json({ results });
        }else{
            return res.status(404).json({ message: "Report not found" });
        }
    } catch (error) {
        console.error("Error fetching report:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

export default medicalReport;