import { BaseCommand, flags } from '@adonisjs/core/ace'
import type { CommandOptions } from '@adonisjs/core/types/ace'
import { DateTime } from 'luxon'

import Post from '#models/post'
import { renderPost } from '#services/blog_renderer'
import { seedArticles } from '#database/seeders/blog_seed/index'

/**
 * Insère / met à jour les articles fondateurs du blog en DB.
 *
 *   node ace seed:blog                # idempotent, upsert par slug
 *   node ace seed:blog --reset        # supprime tous les posts avant
 *
 * À lancer une fois en local et en prod après le déploiement de PR1
 * (avant la mise en route du routing Traefik en PR2). Les ré-exécutions
 * sont sans effet de bord — utile si on retouche les MD source.
 */
export default class SeedBlog extends BaseCommand {
  static commandName = 'seed:blog'
  static description = 'Seed des 3 articles fondateurs du blog (idempotent par slug)'

  static options: CommandOptions = {
    startApp: true,
  }

  @flags.boolean({
    description: 'Supprime tous les posts existants avant le seed',
    default: false,
  })
  declare reset: boolean

  async run() {
    if (this.reset) {
      const deleted = await Post.query().delete()
      this.logger.warning(`${deleted} posts supprimés (--reset).`)
    }

    let created = 0
    let updated = 0

    for (const draft of seedArticles) {
      const { contentHtml, wordCount, readingTimeMinutes } = renderPost(draft.contentMd)
      const publishedAt = DateTime.now().minus({ days: draft.publishedDaysAgo }).toUTC().startOf('minute')

      const existing = await Post.findBy('slug', draft.slug)
      const payload = {
        slug: draft.slug,
        title: draft.title,
        excerpt: draft.excerpt,
        contentMd: draft.contentMd,
        contentHtml,
        authorName: draft.authorName,
        tags: draft.tags,
        status: 'published' as const,
        publishedAt,
        wordCount,
        readingTimeMinutes,
        aiGenerated: false,
        noindex: false,
      }

      if (existing) {
        existing.merge(payload)
        await existing.save()
        updated += 1
      } else {
        await Post.create(payload)
        created += 1
      }

      this.logger.success(`✓ ${draft.slug} (${wordCount} mots, ${readingTimeMinutes} min)`)
    }

    this.logger.info(`\nFait : ${created} créé(s), ${updated} mis à jour, ${seedArticles.length} total.`)
  }
}
