import bcrypt from "bcryptjs";
import User from "../models/User.js";
import generateToken from "../utils/generateToken.js";
import { ApiError, asyncHandler } from "../utils/helpers.js";

export const register = asyncHandler(async (req, res) => {
    const { username, password, age, role } = req.body;
    if (!username || !password || !age || !role) {
        throw new ApiError(400, "Missing required fields");
    }

    const doesExist = await User.findOne({ username });
    if (doesExist) {
        throw new ApiError(400, "Username already exists");
    }

    const hashedPassword = await bcrypt.hash(password, 10);
    const user = await User.create({ username, password: hashedPassword, age, role });

    const tokenPayload = { userId: user._id, username: user.username, role: user.role };
    generateToken(tokenPayload, res);

    res.status(201).json({ message: "Registration successful" });
});

export const login = asyncHandler(async (req, res) => {
    const { username, password } = req.body;
    if (!username || !password) {
        throw new ApiError(400, "Missing required fields");
    }

    const user = await User.findOne({ username });
    if (!user) {
        throw new ApiError(401, "Invalid username or password");
    }

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
        throw new ApiError(401, "Invalid username or password");
    }

    const tokenPayload = { userId: user._id, username: user.username, role: user.role };
    generateToken(tokenPayload, res);

    res.status(200).json({ message: "Login successful" });
});

export const checkAuth = asyncHandler(async (req, res) => {
    res.status(200).json({ username: req.username, role: req.role, id: req.id });
});

export const logout = asyncHandler(async (req, res) => {
    res.clearCookie("jwt");
    res.status(200).json({ message: "Logged out successfully" });
});