/* Seed the studio with the EXACT values from the original site/data.js
   (exported to scripts/seed-data.json). Idempotent: clears the seeded
   collections/globals first so re-running is safe.

   Run:  npm run seed        (after the app is configured + DB reachable)
*/
import { getPayload } from 'payload'
import config from '../src/payload.config'
import { readFileSync } from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const dirname = path.dirname(fileURLToPath(import.meta.url))
const DATA = JSON.parse(readFileSync(path.resolve(dirname, 'seed-data.json'), 'utf8'))

async function run() {
  const payload = await getPayload({ config })

  // --- wipe seeded data (not users/media) so re-seeding is clean ---
  for (const slug of ['markets', 'pricing', 'addons', 'pillars', 'cityScenes'] as const) {
    await payload.delete({ collection: slug, where: {}, overrideAccess: true }).catch(() => {})
  }

  // --- markets ---
  for (const code of Object.keys(DATA.MARKETS)) {
    const m = DATA.MARKETS[code]
    await payload.create({
      collection: 'markets', overrideAccess: true,
      data: {
        code: m.code, name: m.name, fullName: m.fullName, flag: m.flag,
        currency: m.currency, hub: m.hub, hubAddress: m.hubAddress,
        partners: m.partners, upcomingHubs: m.upcomingHubs,
        phone: m.phone, email: m.email, fleetStats: m.fleetStats,
      },
    })
  }

  // --- pricing ---
  for (const code of Object.keys(DATA.PRICING)) {
    const p = DATA.PRICING[code]
    await payload.create({
      collection: 'pricing', overrideAccess: true,
      data: { market: code, daily: p.daily, weekly: p.weekly, monthly: p.monthly },
    })
  }

  // --- addons ---
  for (const code of Object.keys(DATA.ADDONS)) {
    await payload.create({
      collection: 'addons', overrideAccess: true,
      data: {
        market: code,
        items: DATA.ADDONS[code].map((a: any) => ({
          addonId: a.id, name: a.name, price: a.price ?? null,
          suggested: !!a.suggested, included: !!a.included,
        })),
      },
    })
  }

  // --- pillars ---
  await Promise.all(DATA.PILLARS.map((p: any, i: number) =>
    payload.create({
      collection: 'pillars', overrideAccess: true,
      data: { order: i, n: p.n, title: p.title, sub: p.sub, body: p.body, metric: p.metric, metricLabel: p.metricLabel, cite: p.cite },
    })))

  // --- city scenes (keep original path as fallbackImg so the site stays intact) ---
  await Promise.all(DATA.CITY_SCENES.map((c: any, i: number) =>
    payload.create({
      collection: 'cityScenes', overrideAccess: true,
      data: { order: i, sceneId: c.id, label: c.label, fallbackImg: c.img },
    })))

  // --- product global (EPCO X1) ---
  const x = DATA.EPCO_X1
  await payload.updateGlobal({
    slug: 'product', overrideAccess: true,
    data: {
      name: x.name, tagline: x.tagline, pitch: x.pitch,
      specs: Object.keys(x.specs).map((k) => ({ key: k, ...x.specs[k] })),
      features: x.features,
      views: x.views.map((v: any) => ({ viewId: v.id, label: v.label, en: v.en, file: v.file })),
      details: x.details.map((d: any) => ({ detailId: d.id, label: d.label, en: d.en, desc: d.desc, file: d.file })),
      colorways: x.colorways.map((c: any) => ({ colorId: c.id, name: c.name, hex: c.hex, file: c.file })),
    },
  })

  // images global left empty -> front-end keeps built-in placeholders until uploaded

  payload.logger.info('✅ Seed complete: markets, pricing, addons, pillars, cityScenes, product.')
  process.exit(0)
}

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