"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.authenticateSocket = exports.authenticateToken = void 0;
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const database_js_1 = require("../config/database.js");
const env_js_1 = require("../config/env.js");
const authenticateToken = (req, res, next) => {
    try {
        const authHeader = req.headers.authorization;
        const token = authHeader?.split(" ")[1];
        if (!token) {
            res.status(401).json({ success: false, error: "Access token required" });
            return;
        }
        const decoded = jsonwebtoken_1.default.verify(token, env_js_1.env.JWT_SECRET);
        req.user = decoded;
        next();
    }
    catch (error) {
        console.error("Authentication error:", error);
        res.status(403).json({ success: false, error: "Invalid or expired token" });
    }
};
exports.authenticateToken = authenticateToken;
const authenticateSocket = async (socket, next) => {
    try {
        const token = socket.handshake.auth.token;
        if (!token) {
            return next(new Error("Authentication token required"));
        }
        const decoded = jsonwebtoken_1.default.verify(token, env_js_1.env.JWT_SECRET);
        const user = await database_js_1.prisma.user.findUnique({
            where: {
                id: decoded.userId,
            },
        });
        if (!user)
            return next(new Error("User not found"));
        const authenticateSocket = socket;
        authenticateSocket.userId = user.id;
        authenticateSocket.user = user;
        next();
    }
    catch (error) {
        console.error("Socket authentication error:", error);
    }
};
exports.authenticateSocket = authenticateSocket;
