"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 bcryptjs_1 = __importDefault(require("bcryptjs"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const index_1 = require("../index");
const errorHandler_1 = require("../middleware/errorHandler");
const auth_1 = require("../middleware/auth");
const joi_1 = __importDefault(require("joi"));
const router = (0, express_1.Router)();
const loginSchema = joi_1.default.object({
    username: joi_1.default.string().required(),
    password: joi_1.default.string().required(),
});
router.post('/login', (0, errorHandler_1.asyncHandler)(async (req, res) => {
    const { error, value } = loginSchema.validate(req.body);
    if (error) {
        return res.status(400).json({
            success: false,
            message: error.details[0].message,
        });
    }
    const { username, password } = value;
    const admin = await index_1.prisma.adminUser.findUnique({
        where: { username },
    });
    if (!admin) {
        return res.status(401).json({
            success: false,
            message: 'Invalid credentials',
        });
    }
    const isValidPassword = await bcryptjs_1.default.compare(password, admin.passwordHash);
    if (!isValidPassword) {
        return res.status(401).json({
            success: false,
            message: 'Invalid credentials',
        });
    }
    await index_1.prisma.adminUser.update({
        where: { id: admin.id },
        data: { lastLogin: new Date() },
    });
    const jwtSecret = process.env['JWT_SECRET'];
    const jwtExpiresIn = process.env['JWT_EXPIRES_IN'] || '24h';
    if (!jwtSecret) {
        return res.status(500).json({
            success: false,
            message: 'Server configuration error',
        });
    }
    const token = jsonwebtoken_1.default.sign({
        userId: admin.id,
        username: admin.username
    }, jwtSecret, {
        expiresIn: jwtExpiresIn
    });
    res.json({
        success: true,
        message: 'Login successful',
        token,
        user: {
            id: admin.id,
            username: admin.username,
        },
    });
}));
router.get('/verify', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    res.json({
        success: true,
        message: 'Token is valid',
        user: req.user,
    });
}));
router.post('/logout', auth_1.authenticateToken, (0, errorHandler_1.asyncHandler)(async (req, res) => {
    res.json({
        success: true,
        message: 'Logged out successfully',
    });
}));
exports.default = router;
//# sourceMappingURL=auth.js.map