import User from '#models/user'
import { loginValidator } from '#validators/user'
import type { HttpContext } from '@adonisjs/core/http'
import { emitAuthSession } from '#services/auth_session'
import { revokeCurrentRefreshToken } from '#services/refresh_token'

export default class AccessTokensController {
  /**
   * POST /auth/login — vérifie credentials + émet AuthSession.
   */
  async store(ctx: HttpContext) {
    const { email, password } = await ctx.request.validateUsing(loginValidator)

    const user = await User.verifyCredentials(email, password)
    const session = await emitAuthSession(user, ctx)
    return ctx.serialize(session)
  }

  /**
   * POST /account/logout — révoque l'access token courant + le refresh
   * token + clear le cookie.
   */
  async destroy(ctx: HttpContext) {
    const user = ctx.auth.getUserOrFail()
    if (user.currentAccessToken) {
      await User.accessTokens.delete(user, user.currentAccessToken.identifier)
    }
    await revokeCurrentRefreshToken(ctx)

    ctx.response.status(204)
    return null
  }
}
