import { DateTime } from 'luxon'
import User from '#models/user'
import UserTransformer from '#transformers/user_transformer'
import env from '#start/env'
import { issueRefreshToken } from '#services/refresh_token'
import type { HttpContext } from '@adonisjs/core/http'

/**
 * Émet une AuthSession complète : access token en JSON + refresh token
 * en cookie httpOnly. Utilisé par signup et login.
 *
 * Format de réponse aligné sur packages/shared/src/types/auth.ts :
 * `{ data: { accessToken, expiresAt, user } }`
 */
export async function emitAuthSession(
  user: User,
  ctx: HttpContext
): Promise<{
  accessToken: string
  expiresAt: string
  user: ReturnType<UserTransformer['toObject']>
}> {
  const accessToken = await User.accessTokens.create(user)
  await issueRefreshToken(user, ctx)

  const ttlMin = env.get('ACCESS_TOKEN_TTL_MINUTES', 30)
  const expiresAt =
    accessToken.expiresAt?.toISOString() ??
    DateTime.now().plus({ minutes: ttlMin }).toISO()!

  return {
    accessToken: accessToken.value!.release(),
    expiresAt,
    user: new UserTransformer(user).toObject(),
  }
}
