import { AuthenticationException } from '@adonisjs/auth/build/standalone'
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { UserRoles } from 'App/Models/User'
import { schema, rules } from '@ioc:Adonis/Core/Validator'
import UserService from 'App/Services/UserService'

export default class AuthController {
    public async login({ request, auth }: HttpContextContract) {
        const { username, password } = request.all()
        return await auth.use('api').attempt(username, password, {
            expiresIn: '1 year'
        })
    }

    public async loginAdmin({ request, auth }: HttpContextContract) {
        const { username, password } = request.all()
        let token
        try {
            token = await auth.use('api').attempt(username, password, {
                expiresIn: '30 days'
            })
        } catch (error) {
            throw new AuthenticationException(error.message, error.code)
        }
        if (token.user.role === UserRoles.User) {
            throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS')
        }
        return token
    }

    public async register({ request, auth }: HttpContextContract) {
        const data = await request.validate({
            schema: schema.create({
                username: schema.string.optional({ trim: true }, [
                    rules.regex(/^[a-zA-Z0-9_]{4,16}$/),
                    rules.unique({ table: 'users', column: 'username' })
                ]),
                email: schema.string.optional({ trim: true }, [
                    rules.email(),
                    rules.unique({ table: 'users', column: 'email' })
                ]),
                password: schema.string({ trim: true }, [rules.minLength(6), rules.maxLength(18)])
            }),
            messages: {
                minLength: 'The min length of {{field}} is {{ options.minLength }}',
                maxLength: 'The max length of {{field}} is {{ options.maxLength }}',
                unique: '{{field}} not available',
                email: '{{field}} is not a valid email',
                regex: '{{field}} is not valid'
            }
        })
        const user = await UserService.register(data)
        return await auth.use('api').login(user)
    }
}
