import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import User from 'App/Models/User'
import { randomString } from 'App/Utils/random'

/** Login a user that is not using the CAS */
export const loginNotSigmaUser = async ({ request, response, auth }: HttpContextContract) => {
  // TODO: Validate

  const username = request.input('username')
  const password = request.input('password')

  try {
    const token = await auth.use('api').attempt(username, password)
    return response.ok(token)
  } catch {
    return response.unauthorized({ error: 'Identifiants incorrects' })
  }
}

/** Create a user that is not using the CAS */
export const createNotSigmaUser = async ({ request, response }: HttpContextContract) => {
  // TODO: Validate
  const username = request.input('username')
  const name = request.input('name')

  const password = randomString(20)

  // Check if user already exists
  const user = await User.findBy('username', username)

  if (user) {
    return response.badRequest({ error: 'User already exists' })
  }

  await User.create({ username, name, password, groups: [], isAdmin: false, isSigmaUser: false })

  return response.created({ message: 'User created', username, name, password })
}

/** Remove an auth token */
export const logout = async ({ auth }: HttpContextContract) => {
  await auth.use('api').revoke()

  return { message: 'You are now disconnected' }
}