import { Request, Response } from 'express';
import UserDatabaseService, { IUserListService } from '../services/db/userList';
import { Id } from '../declarations/validations';

export class UserController {
    public userListService: IUserListService = new UserDatabaseService();

    //async registerUser(req: Request, res: Response) {
    //    const { password, mail } = req.body;
    //
    //    const username = mail;
    //
    //    // move to frontend too
    //    const errors = [];
    //    if (!username || !password) {
    //        errors.push({ message: 'Please enter all fields' });
    //    }
    //    if (password.length < 6) {
    //        errors.push({
    //            message: 'Psasword should be at least 6 characters',
    //        });
    //    }
    //    if (errors.length > 0) {
    //        // error
    //    } else {
    //        // Form evaluation has passed
    //    }
    //
    //    if (
    //        !username ||
    //        !password ||
    //        //!PasswordPolicy.checkPasswordPolicy(password) ||
    //
    //        !(await this.checkUsernamePolicy(username))
    //    ) {
    //        res.status(400).send({ error: 'Invalid input' });
    //        return;
    //    }
    //
    //    const hashedPassword = await PasswordMgmt.generatePasswordHash(
    //        password
    //    );
    //    this.userListService
    //        .insertUser(username, hashedPassword, mail)
    //        .then((value) =>
    //            res.send({ success: 'User successfully created' })
    //        );
    //}

    //async checkUsernamePolicy(username: string) {
    //    return this.userListService
    //        .findUserByUsername(username)
    //        .then((user) => user === null);
    //}

    //getUser(req: Request, res: Response) {
    //    console.log('Display user');
    //}

    removeUser(req: Request, res: Response) {
        const idInput = parseInt(req.params.id, 10);

        const result = Id.safeParse(idInput);

        if (!result.success) {
            res.status(400).send({ error: 'Invalid identifier' });
            return;
        }

        const id = result.data;

        this.userListService
            .deleteUser(id)
            .then((deletedUser) =>
                res.send({
                    success: `User with id ${id} successfully deleted.`,
                    user: deletedUser,
                })
            )
            .catch(() => {
                res.sendStatus(500);
            });
    }
}

export const userController = new UserController();
