import User from '#models/user';
import env from '#start/env';
import mail from '@adonisjs/mail/services/main';
export default class AuthController {
    async login({ request, response }) {
        const { email, password } = request.only(['email', 'password']);
        try {
            const user = await User.verifyCredentials(email, password);
            const prev = await User.accessTokens.all(user);
            prev.forEach(async (t) => {
                await User.accessTokens.delete(user, t.identifier);
            });
            const token = await User.accessTokens.create(user);
            const tokenValue = token.toJSON().token;
            response.clearCookie('auth_token');
            response.encryptedCookie('auth_token', tokenValue, {
                httpOnly: true,
                maxAge: '7d',
                secure: true,
                sameSite: 'none',
            });
            return response.status(200).json({ ...user.serialize(), credentials: token });
        }
        catch (error) {
            console.log(error);
            return response.unauthorized('Invalid credentials');
        }
    }
    async makeadmin() {
        await User.firstOrCreate({ email: 'admin@cronos.io' }, { password: 'qwerty12' });
        return { created: true };
    }
    async whoiam({ auth, response }) {
        const user = auth.user;
        return response.status(200).json({ ...user.serialize() });
    }
    async changePassword({ auth, request, response }) {
        const user = auth.user;
        const { oldPassword, newPassword } = request.only(['oldPassword', 'newPassword']);
        try {
            await User.verifyCredentials(user.email, oldPassword);
        }
        catch {
            return response.unauthorized('Invalid credentials');
        }
        user.password = newPassword;
        await user.save();
        return response.ok({ changed: true });
    }
    async recoverPassword({ request, response }) {
        const { email } = request.only(['email']);
        const user = await User.findBy('email', email);
        if (!user) {
            return response.notFound({ message: 'User not found' });
        }
        const newPassword = Math.random().toString(36).slice(-8);
        user.password = newPassword;
        await user.save();
        await mail.sendLater((message) => {
            message
                .to(user.email)
                .from(env.get('SMTP_USERNAME'))
                .subject('Cronos, Recuperación de Contraseña')
                .htmlView('emails/recover_password', { password: newPassword });
        });
        return response.ok({ sent: true });
    }
    async testmail({ request, response }) {
        try {
            const { email } = request.only(['email']);
            await mail.send((message) => {
                message
                    .to(email)
                    .from(env.get('SMTP_USERNAME'))
                    .subject('Test de Email')
                    .htmlView('emails/test_email');
            });
            return response.ok({ sent: true });
        }
        catch (error) {
            console.log(error);
            return response.internalServerError({ sent: false, error: error.message });
        }
    }
    async logout({ auth, response }) {
        try {
            const user = auth.user;
            const prev = await User.accessTokens.all(user);
            prev.forEach(async (t) => {
                await User.accessTokens.delete(user, t.identifier);
            });
        }
        catch (error) {
            console.debug('auth.logout() failed or not supported in this context');
        }
        response.clearCookie('auth_token');
        return response.ok({ loggedOut: true });
    }
}
//# sourceMappingURL=auth_controller.js.map