import AuthService from '../services/AuthService.js';
import {validationResult} from 'express-validator';
import ApiError from './ErrorController.js';

class AuthController {
    async register(req, res, next) {
        try {
            const errors = validationResult(req);
            if(!errors.isEmpty()) {
                return next(ApiError.BadRequest('Ошибка при валидации', errors.array()));
            }
            const {email, name, sname, password} = req.body;
            const user = await AuthService.register({email, name, sname, password});
            res.cookie('refreshToken', user.refreshToken, {maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true });
            return res.json(user);
        } catch (e) {
            next(e);
        }
    }
    async login(req, res, next) {
        try {
            const {email, password} = req.body;
            const user = await AuthService.login({email, password});
            res.cookie('refreshToken', user.refreshToken, {maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true });
            return res.json(user);
        } catch (e) {
            next(e);
        }
    }
    async confirm(req, res, next) {
        try {
            const { id } = req.body;
            const confirmation = await AuthService.confirm({ id });
            return res.json(confirmation);
        } catch (e) {
            next(e);
        }
    }
    async logout(req, res, next) {
        try {
            const { refreshToken } = req.cookies;
            const token = await AuthService.logout(refreshToken);
            res.clearCookie('refreshToken');
            return res.json(token);
        } catch (e) {
            next(e);
        }
    }
    async refresh(req, res, next) {
        try {
            const { refreshToken } = req.cookies;
            const user = await AuthService.refresh(refreshToken);
            res.cookie('refreshToken', user.refreshToken, {maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true });
            return res.json(user);
        } catch (e) {
            next(e);
        }
    }
    async test(req, res, next) {
        try {
            res.json('test');
        } catch (e) {
            next(e);
        }
    }
}

export default new AuthController();