#!/usr/bin/env node
/**
 * Fix CMS page **createdAt** (`createdAt` on PUT → epoch milliseconds) for specific blog posts.
 * Leaves **publish schedule** (`schedule.startDate`) unchanged.
 *
 * The path segment in `bildit.co/blogs/<id>/` is not the CMS page document id — this script
 * uses **slugs** resolved from each article’s title (matched to your CMS page list).
 *
 * Run:
 *   BILD_APP_ID=<app-id> node scripts/fix-blog-publish-dates.js
 *   node scripts/fix-blog-publish-dates.js <app-id>
 *
 * Optional: --dry-run
 */

'use strict'

const { updatePageCreatedAt } = require('../src/lib/pages-cli')
const { TARGET_BLOG_ROWS } = require('./lib/blog-metadata-target-rows')

/** @type {{ slug: string, createdAtIso: string, note?: string }[]} */
const UPDATES = TARGET_BLOG_ROWS

async function main() {
  const dryRun = process.argv.includes('--dry-run')
  const positional = process.argv.slice(2).filter((a) => a !== '--dry-run')

  const appId = (process.env.BILD_APP_ID && String(process.env.BILD_APP_ID).trim()) || positional[0]

  if (!appId) {
    console.error(
      'Set BILD_APP_ID or pass app id:\n  BILD_APP_ID=<id> node scripts/fix-blog-publish-dates.js\n  node scripts/fix-blog-publish-dates.js <app-id>'
    )
    process.exit(1)
  }

  /** @type {{ ok: boolean; key: string; detail?: string }[]} */
  const log = []

  for (const row of UPDATES) {
    const key = `slug:${row.slug}`
    const label = row.note ?? row.createdAtIso

    if (dryRun) {
      console.log(`[dry-run] ${key} createdAt→ ${row.createdAtIso} (${label})`)
      log.push({ ok: true, key })
      continue
    }
    try {
      await updatePageCreatedAt(appId, { slug: row.slug }, row.createdAtIso)
      console.log(`ok ${key} (${label})`)
      log.push({ ok: true, key })
    } catch (e) {
      const msg = e && typeof e.message === 'string' ? e.message : String(e)
      console.error(`fail ${key}: ${msg}`)
      log.push({ ok: false, key, detail: msg })
    }
  }

  const fails = log.filter((x) => !x.ok)
  if (fails.length) {
    console.error(`\n${fails.length} update(s) failed.`)
    process.exit(1)
  }
}

main().catch((e) => {
  console.error(e)
  process.exit(1)
})
