import { Exception } from '@adonisjs/core/build/standalone';

/*
|--------------------------------------------------------------------------
| Exception
|--------------------------------------------------------------------------
|
| The Exception class imported from '@adonisjs/core' allows defining
| a status code and error code for every exception.
|
| @example
| new InvalidCredentialException('message', 403, 'E_RUNTIME_EXCEPTION')
|
*/

export default class InvalidCredentialException extends Exception {
    // constructor() {
    //     super(...arguments);
    //     // this.responseText = this.message;
    // }

    /**
     * Unable to find user
     */
    public static invalidUid() {
        const error = new this('User not found', 400, 'E_INVALID_AUTH_UID');
        return error;
    }
    /**
     * Invalid user password
     */
    public static invalidPassword() {
        const error = new this('Password mis-match', 400, 'E_INVALID_AUTH_PASSWORD');
        return error;
    }

    /**
     * Flash error message and redirect the user back
     */
    private respondWithRedirect(error, ctx) {
        // if (!ctx.session) {
        //     return ctx.response.status(this.status).send(this.responseText);
        // }
        ctx.session.flashExcept(['_csrf']);
        ctx.session.flash('auth', {
            error: error,
            /**
             * Will be removed in the future
             */
            errors: {
                uid: this.code === 'E_INVALID_AUTH_UID' ? ['Invalid login id'] : null,
                password: this.code === 'E_INVALID_AUTH_PASSWORD' ? ['Invalid password'] : null,
            },
        });
        ctx.response.redirect('back', true);
    }

    /**
     * Handle this exception by itself
     */

    public handle(error, ctx) {
        //  return response.status(403).view.render("errors/unauthorized", {
        //    error: error,
        //  });
        this.respondWithRedirect(error, ctx);
    }
}
