"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 User_1 = require("../entity/User");
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
const data_source_1 = require("../data-source");
const router = (0, express_1.Router)();
router.post('/login', async (req, res) => {
    try {
        const UserRepository = data_source_1.AppDataSource.getRepository(User_1.User);
        const user = await UserRepository.findOne({
            where: [
                { userName: req.body.userName, password: req.body.password, enable: true },
                { email: req.body.userName, password: req.body.password, enable: true }
            ]
        });
        if (!user)
            return res.sendStatus(401);
        const token = jsonwebtoken_1.default.sign({ user }, process.env.ACCESS_TOKEN_SECRET);
        user.password = null;
        res.send({ user, token });
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
router.post('/register', async (req, res) => {
    try {
        const UserRepository = data_source_1.AppDataSource.getRepository(User_1.User);
        req.body.user.password = req.body.password;
        const user = UserRepository.create(req.body.user);
        const results = await UserRepository.save(user);
        res.send(results);
    }
    catch (error) {
        console.error(error);
        res.sendStatus(500);
    }
});
exports.default = router;
