import User from '#models/user'
import Organization from '#models/organization'
import { signupValidator } from '#validators/user'
import type { HttpContext } from '@adonisjs/core/http'
import db from '@adonisjs/lucid/services/db'
import { provisionDefaultPlans } from '#services/default_plans'
import { emitAuthSession } from '#services/auth_session'

export default class NewAccountController {
  /**
   * POST /auth/signup
   * Crée organisation + 4 plans pré-fournis + user dans une transaction,
   * puis émet une AuthSession (access token JSON + refresh cookie httpOnly).
   */
  async store(ctx: HttpContext) {
    const { fullName, email, password } = await ctx.request.validateUsing(signupValidator)

    const user = await db.transaction(async (trx) => {
      const org = await Organization.create({ name: '' }, { client: trx })
      await provisionDefaultPlans(org.id, trx)
      return User.create(
        { email, password, fullName, organizationId: org.id },
        { client: trx }
      )
    })

    const session = await emitAuthSession(user, ctx)
    ctx.response.status(201)
    return ctx.serialize(session)
  }
}
