"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const db_1 = require("../db");
const schema_1 = require("../db/schema");
const drizzle_orm_1 = require("drizzle-orm");
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const auth_1 = require("../middleware/auth");
const socket_instance_1 = require("../socket-instance");
const router = (0, express_1.Router)();
const JWT_SECRET = process.env.JWT_SECRET || "supersecretkey";
// Register
router.post("/register", async (req, res) => {
    try {
        const { email, password, name } = req.body;
        if (!email || !password || !name) {
            console.log(`Registration failed: Missing fields (${email}, ${name})`);
            return res.status(422).json({ error: "Email, password, and name are required" });
        }
        // Check existing
        const existing = await db_1.db.select().from(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.email, email));
        if (existing.length > 0) {
            console.log(`Registration failed: User already exists (${email})`);
            return res.status(400).json({ error: "User already exists" });
        }
        const hashedPassword = await bcryptjs_1.default.hash(password, 10);
        const id = crypto.randomUUID();
        await db_1.db.insert(schema_1.users).values({
            id,
            email,
            password: hashedPassword,
            name,
            role: "employee",
        });
        const token = jsonwebtoken_1.default.sign({ id, email, name, role: "employee" }, JWT_SECRET, { expiresIn: "10h" });
        const newUser = { id, email, name, role: "employee" };
        // Emit real-time event
        (0, socket_instance_1.getIO)().emit("user_created", newUser);
        res.json({ token, user: newUser });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
// Login
router.post("/login", async (req, res) => {
    try {
        const { email, password } = req.body;
        const user = await db_1.db.select().from(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.email, email));
        if (user.length === 0) {
            console.log(`Login failed: User not found (${email})`);
            return res.status(400).json({ error: "Invalid credentials" });
        }
        const validPassword = await bcryptjs_1.default.compare(password, user[0].password);
        if (!validPassword) {
            console.log(`Login failed: Invalid password for ${email}`);
            return res.status(400).json({ error: "Invalid credentials" });
        }
        const token = jsonwebtoken_1.default.sign({ id: user[0].id, email: user[0].email, name: user[0].name, role: user[0].role }, JWT_SECRET, { expiresIn: "24h" });
        res.json({
            token,
            user: {
                id: user[0].id,
                email: user[0].email,
                name: user[0].name,
                role: user[0].role,
            },
        });
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
// Get current user profile
router.get("/me", auth_1.authenticateToken, async (req, res) => {
    try {
        const userList = await db_1.db.select().from(schema_1.users).where((0, drizzle_orm_1.eq)(schema_1.users.id, req.user.id)).limit(1);
        if (userList.length === 0) {
            return res.status(404).json({ error: "User not found" });
        }
        const { password, ...userWithoutPassword } = userList[0];
        res.json(userWithoutPassword);
    }
    catch (error) {
        console.error(error);
        res.status(500).json({ error: "Server error" });
    }
});
exports.default = router;
