import Organization from '#models/organization'
import OrganizationTransformer from '#transformers/organization_transformer'
import { updateOrganizationValidator } from '#validators/organization'
import type { HttpContext } from '@adonisjs/core/http'
import { Exception } from '@adonisjs/core/exceptions'
import { DateTime } from 'luxon'

export default class OrganizationsController {
  /**
   * GET /organizations/me — l'organisation de l'utilisateur courant.
   */
  async show({ auth, serialize }: HttpContext) {
    const user = auth.getUserOrFail()
    if (user.organizationId === null) {
      throw new Exception('Aucune organisation rattachée', { status: 404, code: 'not_found' })
    }
    const org = await Organization.findOrFail(user.organizationId)
    return serialize(OrganizationTransformer.transform(org))
  }

  /**
   * PATCH /organizations/me — onboarding step 2.
   * Marque `onboardingCompletedAt` dès qu'un nom est posé pour la
   * première fois (heuristique simple : pour l'instant un nom non vide
   * suffit à considérer l'organisation comme "configurée").
   */
  async update({ auth, request, serialize }: HttpContext) {
    const user = auth.getUserOrFail()
    if (user.organizationId === null) {
      throw new Exception('Aucune organisation rattachée', { status: 404, code: 'not_found' })
    }
    const payload = await request.validateUsing(updateOrganizationValidator)

    const org = await Organization.findOrFail(user.organizationId)
    const wasUnnamed = org.name.trim().length === 0

    org.merge(payload)

    if (wasUnnamed && (payload.name?.trim().length ?? 0) > 0 && !org.onboardingCompletedAt) {
      org.onboardingCompletedAt = DateTime.now()
    }

    await org.save()

    return serialize(OrganizationTransformer.transform(org))
  }
}
