"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.changePasswordRoute = void 0;
const bcryptjs_1 = __importDefault(require("bcryptjs"));
const common_1 = require("@tensei/common");
exports.changePasswordRoute = (0, common_1.route)('Change password')
    .post()
    .authorize(({ user }) => !!user)
    .handle(async (request, response) => {
    var _a;
    try {
        await request.config.indicative.validator.validateAll(request.body, {
            currentPassword: 'required',
            newPassword: 'required|min:12'
        }, {
            'currentPassword.required': 'The current password is required.',
            'newPassword.required': 'The new password is required.'
        });
    }
    catch (error) {
        return response.status(422).json({
            errors: error
        });
    }
    const payload = {
        currentPassword: request.body.currentPassword,
        newPassword: request.body.newPassword
    };
    if (!bcryptjs_1.default.compareSync(payload.currentPassword, (_a = request.user) === null || _a === void 0 ? void 0 : _a.password)) {
        return response.status(422).json({
            errors: [
                {
                    message: 'Your current password is incorrect',
                    field: 'currentPassword'
                }
            ]
        });
    }
    request.user.password = payload.newPassword;
    await request.repositories.adminUsers().persistAndFlush(request.user);
    return response.status(204).json();
});
