import Invoice from '#models/invoice'
import User from '#models/user'
import Organization from '#models/organization'
import { sendPaymentThanksEmail } from '#services/mail_dispatcher'
import { recordActivity } from '#services/activity_recorder'
import logger from '@adonisjs/core/services/logger'

/**
 * Worker BullMQ pour la queue `payment-thanks`. Idempotent au sens où
 * le caller (controllers) n'enqueue que sur transition `* → paid` ; le job
 * lui-même se contente de loader la facture et d'envoyer.
 *
 * Cas no-op silencieux (pas d'erreur — le job réussit) :
 *  - facture introuvable / supprimée
 *  - client sans email (déjà loggué dans sendPaymentThanksEmail)
 *  - utilisateur sans org (anomalie data)
 */
export async function sendPaymentThanksJob(jobData: { invoiceId: string }) {
  logger.info({ invoiceId: jobData.invoiceId }, 'sendPaymentThanksJob: pick-up')

  const invoice = await Invoice.query()
    .where('id', jobData.invoiceId)
    .preload('client')
    .preload('plan')
    .preload('organization')
    .first()
  if (!invoice) {
    logger.warn({ invoiceId: jobData.invoiceId }, 'sendPaymentThanksJob: invoice not found, skip')
    return
  }
  if (!invoice.client?.email) {
    logger.warn(
      { invoiceId: invoice.id, numero: invoice.numero },
      'sendPaymentThanksJob: client sans email, skip'
    )
    return
  }

  const user = await User.query().where('organization_id', invoice.organizationId).first()
  // organization preloaded ci-dessus ; fallback explicite si la relation est null
  // (anomalie data) — on continue avec null, le sender utilisera son fallback brand.
  const organization =
    invoice.organization ?? (await Organization.find(invoice.organizationId)) ?? null

  await sendPaymentThanksEmail({
    invoice,
    client: invoice.client,
    plan: invoice.plan ?? null,
    user: user ?? null,
    organization,
  })

  await recordActivity({
    organizationId: invoice.organizationId,
    kind: 'thanks_email_sent',
    label: `Remerciement envoyé à <b>${invoice.client.name}</b> pour ${invoice.numero}`,
    meta: { invoiceId: invoice.id, clientId: invoice.clientId },
  })

  logger.info(
    { invoiceId: invoice.id, numero: invoice.numero },
    'sendPaymentThanksJob: terminé OK'
  )
}
