"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getProfile = exports.login = void 0;
const createToken_1 = __importDefault(require("./createToken"));
const responseHandler_1 = require("../../../utils/responseHandler");
const bcrypt_1 = __importDefault(require("bcrypt"));
const config_1 = __importDefault(require("../../config"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const users_1 = __importDefault(require("../../models/users"));
const checkPassword = async (password, hashedPassword) => {
    return await bcrypt_1.default.compare(password, hashedPassword);
};
const login = async (req, res) => {
    try {
        if (!req.body) {
            responseHandler_1.ResponseHandler.error(res, "Invalid request", 422);
            return;
        }
        const { email, password } = req.body;
        const errors = [];
        if (!email)
            errors.push("Email");
        if (!password)
            errors.push("Password");
        if (errors.length) {
            responseHandler_1.ResponseHandler.error(res, "Validation error", 422, errors);
            return;
        }
        const user = await users_1.default.scope("withPassword").findOne({ where: { email } });
        if (!user) {
            responseHandler_1.ResponseHandler.error(res, "User not found", 422);
            return;
        }
        if (!(await checkPassword(password, user.password))) {
            responseHandler_1.ResponseHandler.error(res, "Invalid email or password", 422);
            return;
        }
        const userToken = await (0, createToken_1.default)(user.id);
        const userData = user.get();
        const imageUrl = userData.image
            ? `${req.protocol}://${req.get("host")}/images/users/${userData.image.replace(/\\/g, "/")}`
            : `${req.protocol}://${req.get("host")}/assets/images/logo.jpeg`;
        const response = {
            name: userData.name,
            email: userData.email,
            role: null,
            phone: userData.phone,
            token: userToken,
            image: imageUrl,
        };
        responseHandler_1.ResponseHandler.success(res, response, "Login successful");
    }
    catch (err) {
        if (err instanceof Error) {
            responseHandler_1.ResponseHandler.error(res, err.message ?? "Invalid request", 500);
        }
        else {
            responseHandler_1.ResponseHandler.error(res, "Invalid request", 500);
        }
    }
};
exports.login = login;
const getProfile = async (req, res) => {
    // Check for the Authorization header
    const authHeader = req.headers["authorization"];
    if (!authHeader) {
        responseHandler_1.ResponseHandler.error(res, "Missing Authorization header", 422);
        return;
    }
    // Expecting header in the format: "Bearer <token>"
    const parts = authHeader.split(" ");
    if (parts.length !== 2 || parts[0] !== "Bearer") {
        responseHandler_1.ResponseHandler.error(res, "Invalid Authorization header format", 422);
        return;
    }
    const token = parts[1];
    try {
        const decodedToken = jsonwebtoken_1.default.verify(token, config_1.default.SECRET_KEY);
        const userId = decodedToken.sub;
        const user = await users_1.default.findByPk(userId, {
            attributes: ["id", "name", "email", "phone", "role", "image"],
        });
        if (!user) {
            responseHandler_1.ResponseHandler.error(res, "User not found", 422);
            return;
        }
        const userData = user.get();
        const imageUrl = userData.image
            ? `${req.protocol}://${req.get("host")}/images/users/${userData.image.replace(/\\/g, "/")}`
            : `${req.protocol}://${req.get("host")}/assets/images/logo.jpeg`;
        const response = {
            name: userData.name,
            email: userData.email,
            role: null,
            phone: userData.phone,
            image: imageUrl,
        };
        responseHandler_1.ResponseHandler.success(res, response);
    }
    catch (err) {
        responseHandler_1.ResponseHandler.error(res, err.message || "Unauthorized access", 401);
    }
};
exports.getProfile = getProfile;
