// First-run content. When the database has no courses, load the site copy and the five courses from
// seed/content/*.json (the files the static site was built from) and the images from seed/images.
// After that the CMS is the only source: editing the JSON files changes nothing.
import fs from 'fs'
import path from 'path'
import type { Payload } from 'payload'

type Loc = 'ar' | 'en'
type Bi<T = string> = { ar: T; en: T }
const LOCALES: Loc[] = ['ar', 'en']

// the static site's page names → the new addresses
const LEGACY: Record<string, string> = {
  'index.html': '/',
  'courses.html': '/courses',
  'pricing.html': '/pricing',
  'about.html': '/about',
  // The brand guidelines page was taken down on 27 September 2026 (owner's instruction), so a fresh seed
  // must not put a footer link to it back.
}
const link = (h: string) => LEGACY[h] ?? h

const EXTRA: Record<string, Bi> = {
  signIn: { ar: 'دخول المنصة', en: 'Sign in' },
  subscribe: { ar: 'اشترك في المنهج', en: 'Enrol now' },
  sent: {
    ar: 'وصلنا طلبك. سنتواصل معك على البريد أو الموبايل قبل فتح التسجيل.',
    en: 'We have your request. We will contact you by email or mobile before enrolment opens.',
  },
  invalid: {
    ar: 'راجع الاسم والبريد الإلكتروني ثم أرسل مرة أخرى.',
    en: 'Check your name and email, then send again.',
  },
}

export async function seedIfEmpty(payload: Payload): Promise<void> {
  if (process.env.PAYLOAD_SEED === 'off') return
  try {
    await ensureAdmin(payload)
    const { totalDocs } = await payload.count({ collection: 'courses' })
    if (totalDocs > 0) return
    payload.logger.info('seed: empty database, loading the site content')
    await seed(payload)
    payload.logger.info('seed: done')
  } catch (err) {
    payload.logger.error({ err }, 'seed: failed')
  }
}

async function ensureAdmin(payload: Payload) {
  const email = process.env.ADMIN_EMAIL
  const password = process.env.ADMIN_PASSWORD
  if (!email || !password) return
  const { totalDocs } = await payload.count({ collection: 'users' })
  if (totalDocs > 0) return
  await payload.create({ collection: 'users', data: { email, password, name: 'Admin' } })
  payload.logger.info(`seed: administrator ${email} created`)
}

async function seed(payload: Payload) {
  const dir = process.env.SEED_DIR || path.resolve(process.cwd(), 'seed')
  const S = JSON.parse(fs.readFileSync(path.join(dir, 'content/site.json'), 'utf-8'))
  const C = JSON.parse(fs.readFileSync(path.join(dir, 'content/courses.json'), 'utf-8'))
  const courses: any[] = [...C.courses].sort((a, b) => a.order - b.order)

  // ------------------------------------------------ images
  const media: Record<string, number | string> = {}
  const image = async (file: string, alt: Bi) => {
    if (media[file]) return media[file]
    const filePath = path.join(dir, 'images', file)
    if (!fs.existsSync(filePath)) return null
    const doc = await payload.create({ collection: 'media', data: { alt: alt.ar }, filePath, locale: 'ar' })
    await payload.update({ collection: 'media', id: doc.id, data: { alt: alt.en }, locale: 'en' })
    media[file] = doc.id
    return doc.id
  }
  const H = S.home as Bi<any>
  const heroImage = await image('jana.webp', { ar: H.ar.jana_alt, en: H.en.jana_alt })
  const lifeImage = await image('lesson-1-1-koshari.jpg', { ar: H.ar.life_alt, en: H.en.life_alt })

  // ------------------------------------------------ courses
  const ids: Record<string, number | string> = {}
  for (const c of courses) {
    const posterFile = c.preview?.poster ? path.basename(c.preview.poster) : null
    const poster = posterFile ? await image(posterFile, c.preview.poster_note) : null
    const localized = (l: Loc) => ({
      title: c.title[l],
      titleShort: c.title_short?.[l],
      tagline: c.tagline[l],
      audience: c.audience?.[l],
      level: c.level?.[l],
      instruction: c.instruction?.[l],
      availability: c.availability?.[l],
      facts: (c.facts || []).map((f: Bi) => ({ text: f[l] })),
      includes: (c.includes?.[l] || []).map((text: string) => ({ text })),
      outcomes: (c.outcomes?.[l] || []).map((text: string) => ({ text })),
      price: { amount: c.price?.amount ?? null, note: c.price?.note?.[l] },
      posterNote: c.preview?.poster_note?.[l],
    })
    const doc = await payload.create({
      collection: 'courses',
      locale: 'ar',
      data: {
        slug: c.slug,
        status: c.status,
        order: c.order,
        poster: poster ?? undefined,
        videoUrl: c.preview?.video || undefined,
        tone: toneFor(c.slug),
        units: (c.units || []).map((u: any) => ({
          n: u.n,
          name: u.ar,
          lessons: u.lessons,
          book: u.book ?? null,
          kind: u.kind || 'lessons',
          source: u.source || 'book',
        })),
        ...localized('ar'),
      } as any,
    })
    await payload.update({
      collection: 'courses',
      id: doc.id,
      locale: 'en',
      data: {
        ...localized('en'),
        units: (doc.units || []).map((u: any, i: number) => ({ ...u, name: c.units[i].en })),
      } as any,
    })
    ids[c.slug] = doc.id
  }

  // ------------------------------------------------ globals, one language at a time
  for (const l of LOCALES) {
    const h = S.home[l]
    const cp = S.courses_page[l]
    const lp = S.course_page[l]
    const pp = S.pricing_page[l]
    const ap = S.about_page[l]
    const f = S.footer[l]

    await payload.updateGlobal({
      slug: 'settings',
      locale: l,
      data: {
        brandName: S.brand.name[l],
        contact: S.contact,
        platformUrl: 'http://localhost:8881',
        freeLessonHref: '/courses/bacc-en#preview',
        currency: { code: C.currency.code, label: C.currency[l] },
        nav: S.nav[l].map(([label, h]: string[]) => ({ label, href: link(h) })),
        cta: { ...S.cta[l], subscribe: EXTRA.subscribe[l] },
        ui: { langSwitch: S.ui[l].lang_switch, menu: S.ui[l].menu, skip: S.ui[l].skip, signIn: EXTRA.signIn[l] },
        status: cp.status,
        footer: {
          tagline: f.tagline,
          coursesHeading: f.courses,
          academyHeading: f.academy,
          links: f.links.map(([label, h]: string[]) => ({ label, href: link(h) })),
          rights: f.rights,
        },
      } as any,
    })

    await payload.updateGlobal({
      slug: 'home',
      locale: l,
      data: {
        seo: { title: h.title, description: h.description },
        eyebrow: h.eyebrow,
        h1: h.h1[0],
        h1Accent: h.h1[1],
        lead: h.lead,
        facts: h.facts.map(([n, label]: string[]) => ({ n, label })),
        heroImage,
        bookTitle: h.book_title,
        bookLead: h.book_lead,
        bookBarTitle: h.book_bar_title,
        bookBar: h.book_bar.map(([n, label, kind]: string[]) => ({ n, label, kind })),
        bookCode: h.book_code,
        layersTitle: h.layers_title,
        layers: h.layers.map(([badge, name, text]: string[], i: number) => ({ badge, name, text, plain: i === 0 })),
        paths: h.paths,
        stepsTitle: h.steps_title,
        steps: h.steps.map(([n, title, text]: string[]) => ({ n, title, text })),
        lifeTitle: h.life_title,
        lifeText: h.life_text,
        lifeImage,
        lifeBoxes: h.life_boxes.map(([title, text]: string[]) => ({ title, text })),
        unitsTitle: h.units_title,
        unitsLead: h.units_lead,
        unitsCourse: ids['bacc-en'],
        peopleTitle: h.people_title,
        people: h.people.map(([name, text]: string[]) => ({ name, text })),
        coursesTitle: h.courses_title,
        coursesLead: h.courses_lead,
        ctaTitle: h.cta_title,
        ctaLead: h.cta_lead,
        faqTitle: h.faq_title,
        faq: h.faq.map(([q, text]: string[]) => ({ q, text })),
      } as any,
    })

    await payload.updateGlobal({
      slug: 'catalogue',
      locale: l,
      data: {
        seo: { title: cp.title, description: cp.description },
        h1: cp.h1,
        lead: cp.lead,
        labels: {
          back: lp.back,
          outcomes: lp.outcomes,
          audience: lp.audience,
          instruction: lp.instruction,
          level: lp.level,
          units: lp.units,
          unitsLead: lp.units_lead,
          preview: lp.preview,
          previewNote: lp.preview_note,
          lessonsWord: lp.lessons_word,
          labsWord: lp.labs_word,
          projectsWord: lp.projects_word,
          fromBook: lp.from_book,
          added: lp.added,
          addedUnit: lp.added_unit,
        },
      } as any,
    })

    await payload.updateGlobal({
      slug: 'pricing',
      locale: l,
      data: {
        seo: { title: pp.title, description: pp.description },
        h1: pp.h1,
        lead: pp.lead,
        plansTitle: pp.plans_title,
        plans: pp.plans.map(([name, text, items, price]: [string, string, string[], string | null]) => ({
          name,
          text,
          items: items.map((t) => ({ text: t })),
          price: price || null,
        })),
        formTitle: pp.form_title,
        formLead: pp.form_lead,
        fields: pp.fields,
        roles: pp.roles.map((label: string) => ({ label })),
        submit: pp.submit,
        privacy: pp.privacy,
        sent: EXTRA.sent[l],
        invalid: EXTRA.invalid[l],
      } as any,
    })

    await payload.updateGlobal({
      slug: 'about',
      locale: l,
      data: {
        seo: { title: ap.title, description: ap.description },
        h1: ap.h1,
        lead: ap.lead,
        peopleTitle: ap.people_title,
        principlesTitle: ap.principles_title,
        principles: ap.principles.map((text: string) => ({ text })),
        sections: ap.sections.map(([title, text]: string[]) => ({ title, text })),
      } as any,
    })
  }
}

function toneFor(slug: string) {
  return ({ 'bacc-en': 'royal-700', 'bacc-ar': 'royal-800', kids: 'azure-700', advanced: 'navy-900', 'ai-daily': 'navy-700' } as Record<string, string>)[slug] || 'royal-700'
}
