import { Router } from 'express';
import { User } from '../entity/User';
import jwt from 'jsonwebtoken';
import { AppDataSource } from '../data-source';

const router = Router();

router.post('/login', async (req: any, res: any) => {
  try {
    const UserRepository = AppDataSource.getRepository(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 = jwt.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 = AppDataSource.getRepository(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);
  }
});

export default router;