import express from "express";
import bcrypt from "bcryptjs";
import { connection } from "../configs/db.js";
import dotenv from "dotenv"
import { generateCookies, verifyCookies } from "../auth/auth.js";

dotenv.config()

const RECEPTIONIST_CREATION_CODE = parseInt(process.env.RECEPTIONIST_CREATION_CODE);
const DOCTOR_CREATION_CODE = parseInt(process.env.DOCTOR_CREATION_CODE);

const authRouter = express.Router();

authRouter.post("/register", async(req, res) =>{
    try {
        const { username, password, creationCode } = req.body;
        if(!username || !password || !creationCode) return res.status(400).json({ message: "Username, password and creation code are required" });
        let role;
        if(creationCode == RECEPTIONIST_CREATION_CODE) {
            role = "receptionist";
        } else if(creationCode == DOCTOR_CREATION_CODE) {
            role = "doctor";
        } else {
            return res.status(400).json({ message: "Invalid creation code" });
        }
        // console.log(creationCode, RECEPTIONIST_CREATION_CODE, DOCTOR_CREATION_CODE);
        const [existingUsers] = await connection.query("SELECT * FROM users WHERE username = ?", [username]);

        if(existingUsers.length > 0) return res.status(400).json({ message: "Username already exists" });

        const hashedPassword = await bcrypt.hash(password, 10);
        const sql = "INSERT INTO users (username, password, role) VALUES (?, ?, ?)";
        const values = [username, hashedPassword, role];

        const [insertResult] = await connection.query(sql, values);
        const user = { id: insertResult.insertId, role };
        generateCookies(user, res);
        return res.status(201).json({ message: "User created successfully" });
    } catch (error) {
        console.error("authRouter error:", error);
        return res.status(500).json({ message: "Internal Server Error" });
    }
})


//login

authRouter.post("/login", async(req, res) => {
    try {
        const { username, password } = req.body;

        if(!username || !password) return res.status(400).json({ message: "Username and password are required" });

        const sql = "SELECT * FROM users WHERE username = ?";
        const values = [username];
        const [rows] = await connection.query(sql, values);

        if(rows.length == 0) return res.status(400).json({ message: "Invalid username or password" });

        const passwordMatch = await bcrypt.compare(password, rows[0].password);
        if(!passwordMatch) return res.status(400).json({ message: "Invalid username or password" });

        generateCookies(rows[0], res);
        return res.status(200).json({ message: "Logged in successfully" });
    } catch (error) {
        console.error("authRouter error:", error);
        return res.status(500).json({ message: "Internal Server Error" });
    }
})

//logout 

authRouter.post("/logout", verifyCookies, async(req, res) => {
    try {
        res.clearCookie("token");
        return res.status(200).json({ message: "Logged out successfully" });
    } catch (error) {
        console.log(error);
        return res.status(500).json({ message: "Internal Server Error" });
    }
})

//check auth

authRouter.get("/check", verifyCookies, async(req, res) => {
    try {
        const user = req.username;
        const id = req.id;
        const role = req.role;

        return res.status(200).json({ user, id, role });
    } catch (error) {
        console.error("authRouter error:", error);
        return res.status(500).json({ message: "Internal Server Error" });
    }
})

// get doctors

authRouter.get("/doctors", verifyCookies, async(req, res) => {
    try {
        const doctors = await connection.query("SELECT username,id,role FROM users WHERE role = 'doctor'");
        return res.status(200).json({ doctors: doctors[0] });
    } catch (error) {
        console.error("authRouter error:", error);
        return res.status(500).json({ message: "Internal Server Error" });
    }
})

export default authRouter;
