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

const patientRouter = express.Router();

// create patient

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

        const  { full_name, gender, date_of_birth, phone_number, address } = req.body;
        if(!full_name || !gender || !date_of_birth || !phone_number || !address) return res.status(400).json({ message: "Full name, gender, date of birth, phone number and address are required" });
        const sql = "SELECT * FROM patients WHERE full_name = ? AND date_of_birth = ?";
        const [doesExist] = await connection.query(sql, [full_name, date_of_birth]);
        if(doesExist.length > 0) return res.status(400).json({ message: "Patient already exists" });

        const insertSQL = "INSERT INTO patients (full_name, gender, date_of_birth, phone_number, address) VALUES (?, ?, ?, ?, ?)";
        const [insertResult] = await connection.query(insertSQL, [full_name, gender, date_of_birth, phone_number, address]);
        if(insertResult.affectedRows > 0) return res.status(201).json({ message: "Patient created successfully" });
        return res.status(500).json({ message: "Failed to create patient" });
    } catch (error) {
        console.error("Error creating patient:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

// delete patient

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

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

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

// update patient

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

        const { full_name, gender, date_of_birth, phone_number, address } = req.body;
        if(!full_name || !gender || !date_of_birth || !phone_number || !address) return res.status(400).json({ message: "Full name, gender, date of birth, phone number and address are required" });

        const sql = "UPDATE patients SET full_name = ?, gender = ?, date_of_birth = ?, phone_number = ?, address = ? WHERE id = ?";

        const [updateResult] = await connection.query(sql, [full_name, gender, date_of_birth, phone_number, address, id]);
        if(updateResult.affectedRows > 0){
            return res.status(200).json({ message: "Patient updated successfully" });
        }else{
            return res.status(404).json({ message: "Patient not found" });
        }
    } catch (error) {
        console.error("Error updating patient:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

// get patients all

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

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

// get patient by id

patientRouter.get("/:id", verifyCookies, async(req, res) => {
    try {
        const { id } = req.params;
        const sql = "SELECT * FROM patients 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: "Patient not found" });
        }
    } catch (error) {
        console.error("Error fetching patient:", error);
        return res.status(500).json({ message: "Internal server error" });
    }
})

export default patientRouter;