import UserService from '../services/user.js';
import log from '../utils/log.js';
import bcrypt from 'bcrypt';
import genToken from '../utils/jwt.js';
import AbstractProductService from '../services/abstractproduct.js';
import ProductService from '../services/product.js';

const TAG = "/controllers/userjs"

class UserController {
    async register(req, res) {
        try {
            const { username, password } = req.body;

            await UserService.create(username, password);

            log.info(`New user with name ${username} has just registered`);
            return res.status(200).send("Successfull register");
        } catch (e) { res.status(500).send(log.unknownError(`${TAG}/register: ${e}`)); }
    }

    async login(req, res) {
        try {
            const { username, password } = req.body;

            const user = await UserService.getByUsername(username);
            if (!bcrypt.compareSync(password, user.password)) return res.status(401).send("Wrong password");

            const token = genToken(user);
            return res.status(200).send(token);
        } catch (e) { res.status(500).send(log.unknownError(`${TAG}/login: ${e}`)); }
    }

    async synchronize(req, res) {
        try {
            const { groupId } = req.params;

            let result = {};
            result.abstract_products = await AbstractProductService.getAll(groupId);
            result.products = await ProductService.getAll(groupId);
            result.categories = await CategoryService.getAll(groupId);

            return res.status(200).json(result);
        } catch (e) { res.status(500).send(log.unknownError(`${TAG}/synchronize: ${e}`)); }
    }
}

export default new UserController()