import type Plan from '#models/plan'
import type PlanStep from '#models/plan_step'
import { BaseTransformer } from '@adonisjs/core/transformers'

function serializeStep(s: PlanStep) {
  return {
    id: s.id,
    order: s.order,
    offsetDays: s.offsetDays,
    tone: s.tone,
    subject: s.subject,
    body: s.body,
    requiresManualValidation: s.requiresManualValidation,
  }
}

export default class PlanTransformer extends BaseTransformer<Plan> {
  toObject() {
    const p = this.resource
    // p.steps doit être préchargé par le controller (preload('steps'))
    const steps = (p.steps ?? []).slice().sort((a, b) => a.order - b.order)
    return {
      id: p.id,
      organizationId: p.organizationId,
      slug: p.slug,
      name: p.name,
      description: p.description,
      isDefault: p.isDefault,
      steps: steps.map(serializeStep),
      createdAt: p.createdAt.toISO()!,
      updatedAt: p.updatedAt?.toISO() ?? p.createdAt.toISO()!,
    }
  }
}
