/**
 * Content update, 19 September 2026: the whole of Unit 1 is free, the hero speaks plain Egyptian, the three steps
 * use the student's words, and the FAQ answers the three questions a parent asks first (is Unit 1 really free,
 * why the parent's number, how to pay).
 *
 *   docker compose --profile tools run --rm -e NODE_ENV=production tools npx tsx src/scripts/2026-09-19-unit1-free.ts
 *
 * NODE_ENV=production matters: without it Payload runs in dev mode, "pushes" the schema and leaves a `dev` row in
 * payload_migrations, and the site then stops at start-up asking whether to continue (fixed on 19 Sep 2026 by
 * deleting that row).
 *
 * Runs through Payload's local API inside the tools container (no sign-in). Safe to re-run: it sets values, it does
 * not append twice. Before changing anything it writes the current content to src/scripts/backup-2026-09-19.json.
 */
import fs from 'node:fs'
import path from 'node:path'
import { getPayload } from 'payload'
import config from '@payload-config'

type L = 'ar' | 'en'
const payload = await getPayload({ config })
const backup: Record<string, unknown> = {}

const get = (slug: string, locale: L) => payload.findGlobal({ slug: slug as never, locale, depth: 0 }) as Promise<any>
const set = (slug: string, locale: L, data: any) =>
  payload.updateGlobal({ slug: slug as never, locale, data, depth: 0 }) as Promise<any>

for (const g of ['settings', 'catalogue', 'home', 'pricing']) {
  backup[g] = { ar: await get(g, 'ar'), en: await get(g, 'en') }
}
const courses = await payload.find({ collection: 'courses' as never, where: { slug: { equals: 'bacc-en' } }, depth: 0, locale: 'ar' })
const course = courses.docs[0] as any
backup.course = { ar: course, en: await payload.findByID({ collection: 'courses' as never, id: course.id, locale: 'en', depth: 0 }) }
fs.writeFileSync(path.join(process.cwd(), 'src/scripts/backup-2026-09-19.json'), JSON.stringify(backup, null, 2))

const T = {
  ar: {
    free: 'ابدأ الوحدة الأولى ببلاش',
    preview: 'شاهد الدرس الأول، والوحدة الأولى كلها ببلاش',
    availability: 'مش محتاج تدفع عشان تشوف الوحدة الأولى كاملة. الدرسان 1-1 و1-2 متاحان الآن، وباقي الدروس تُنشر درساً بدرس خلال العام الدراسي.',
    posterNote: 'الدرس 1-1 كاملاً، والوحدة الأولى كلها ببلاش',
    h1: 'هتفهم المنهج بالمصري، درس درس.',
    h1Accent: ' والوحدة الأولى كلها ببلاش.',
    lead: 'اتفرّج على الشرح، وراجع نصايح الدرس، وحلّ أسئلة كتير على المنصة. المنهج كما في الكتاب، وفوقه ما يهيّئك لما بعد الامتحان.',
    homeSeo: 'منهج «البرمجة والذكاء الاصطناعي» للصف الثاني الثانوي في البكالوريا المصرية، درساً بدرس: فيديو بشرح مصري، ونصائح الدرس، وأسئلة تحلّها على المنصة. الوحدة الأولى كلها مجاناً.',
    steps: ['اتفرّج على الشرح', 'راجع النصايح', 'حِلّ أسئلة كتير'],
    ctaTitle: 'ابدأ الوحدة الأولى، ببلاش',
    ctaLead: 'سجّل في دقيقة، وبعدها الدروس الأربعة كاملة بنصايحها وأسئلتها. شاهد وقارن، ثم قرّر.',
    faqPay: ['كيف أدفع؟', 'من المنصة بإنستاباي: تحوّل المبلغ، وترفع صورة الإيصال، ونفتح لك الدورة بعد مراجعته. والوحدة الأولى لا تحتاج أي دفع.'],
    faqFree: ['هل الوحدة الأولى مجانية فعلاً؟', 'نعم. الدروس الأربعة كاملة: الفيديو، ونصائح الدرس، والأسئلة، دون أي دفع.'],
    faqParent: ['لماذا تطلبون رقم وليّ الأمر؟', 'لنتواصل مع وليّ الأمر بخصوص دراسة الطالب واشتراكه فقط، ولا نشارك الرقم مع أي جهة.'],
    pricingSeo: 'خطط الاشتراك في أكاديمية Thinkera: الوحدة الأولى كاملة مجاناً، ثم وحدة واحدة أو الدورة كاملة، والدفع بإنستاباي من المنصة.',
    pricingLead: 'الوحدة الأولى كاملة مجاناً. وباقي الدورة بالاشتراك، والدفع بإنستاباي من المنصة.',
    plan0: { name: 'الوحدة الأولى', text: 'الدروس الأربعة كاملة مجاناً، قبل أي اشتراك.', items: ['فيديوهات الدروس الأربعة', 'نصائح كل درس', 'أسئلة كل درس'], price: 'مجاناً' },
    formLead: 'املأ البيانات، وسنرسل لك سعر كل خطة ومواعيد نشر الدروس.',
  },
  en: {
    free: 'Start Unit 1 free',
    preview: 'Watch lesson one; all of Unit 1 is free',
    availability: 'The whole of Unit 1 is free. Lessons 1-1 and 1-2 are available now; the rest are published one by one through the school year.',
    posterNote: 'Lesson 1-1 in full; all of Unit 1 is free',
    h1: 'The syllabus, explained in plain Egyptian Arabic, lesson by lesson.',
    h1Accent: ' And the whole of Unit 1 is free.',
    lead: 'Watch the lesson, review its tips, then practise plenty of questions on the platform. The syllabus as the book has it, plus what prepares you for after the exam.',
    homeSeo: 'The Egyptian Baccalaureate Grade 11 syllabus, Programming and Artificial Intelligence, lesson by lesson: a video explained in Egyptian Arabic, lesson tips, and practice questions on the platform. The whole of Unit 1 is free.',
    steps: ['Watch', 'Review the tips', 'Practise plenty of questions'],
    ctaTitle: 'Start Unit 1, free',
    ctaLead: 'Sign up in a minute, then all four lessons with their tips and quizzes. Watch, compare, then decide.',
    faqPay: ['How do I pay?', 'On the platform, with InstaPay: transfer the amount, upload the receipt, and we open the course once it is checked. Unit 1 needs no payment at all.'],
    faqFree: ['Is Unit 1 really free?', 'Yes. All four lessons in full, video, tips and quizzes, with no payment.'],
    faqParent: ["Why do you ask for a parent's number?", "To contact the parent about the student's studies and subscription only. We do not share the number with anyone."],
    pricingSeo: 'Thinkera Academy plans: Unit 1 free in full, then a single unit or the full course, paid with InstaPay on the platform.',
    pricingLead: 'Unit 1 is free in full. The rest of the course is by subscription, paid with InstaPay on the platform.',
    plan0: { name: 'Unit 1', text: 'All four lessons in full, free, before you subscribe.', items: ['Videos of all four lessons', 'Tips for every lesson', 'Quizzes for every lesson'], price: 'Free' },
    formLead: 'Fill this in and we will send you the price of each plan and when lessons are published.',
  },
}

// Each language is updated on its own; list items keep their ids, so a re-run edits the same items instead of adding more.
for (const locale of ['ar', 'en'] as L[]) {
  const t = T[locale]

  const st = await get('settings', locale)
  await set('settings', locale, { cta: { ...st.cta, free: t.free } })

  const cat = await get('catalogue', locale)
  await set('catalogue', locale, { labels: { ...cat.labels, preview: t.preview } })

  await payload.update({ collection: 'courses' as never, id: course.id, locale,
    data: { availability: t.availability, posterNote: t.posterNote } as never, depth: 0 })

  const h = await get('home', locale)
  const steps = (h.steps || []).map((s: any, i: number) => ({ ...s, title: t.steps[i] ?? s.title }))
  let faq = [...(h.faq || [])]
  const findQ = (q: string, other: string) => faq.findIndex((f: any) => f.q === q || f.q === other)
  // the payment answer replaces the old "announced before enrolment" text (it was the sixth question)
  const payIdx = faq.findIndex((f: any) => /تُعلن|announced|إنستاباي|InstaPay/.test(f.text || ''))
  if (payIdx >= 0) faq[payIdx] = { ...faq[payIdx], q: t.faqPay[0], text: t.faqPay[1] }
  // the two new questions go first: they are what a parent asks before anything else
  for (const [key, pair] of [['free', t.faqFree], ['parent', t.faqParent]] as const) {
    const other = locale === 'ar' ? T.en[key === 'free' ? 'faqFree' : 'faqParent'][0] : T.ar[key === 'free' ? 'faqFree' : 'faqParent'][0]
    const i = findQ(pair[0], other)
    if (i >= 0) faq[i] = { ...faq[i], q: pair[0], text: pair[1] }
    else faq = key === 'free' ? [{ q: pair[0], text: pair[1] }, ...faq] : [faq[0], { q: pair[0], text: pair[1] }, ...faq.slice(1)]
  }
  // the FAQ list is localized as a whole: each language keeps its own rows, so each pass edits only its own list
  // one field per call: two arrays (steps and faq) in a single update hit a unique-id error on PostgreSQL
  const homeData: Record<string, unknown> = {
    h1: t.h1, h1Accent: t.h1Accent, lead: t.lead, seo: { ...h.seo, description: t.homeSeo },
    steps, ctaTitle: t.ctaTitle, ctaLead: t.ctaLead, faq,
  }
  for (const [k, v] of Object.entries(homeData)) await set('home', locale, { [k]: v })

  const p = await get('pricing', locale)
  const plans = [...(p.plans || [])]
  if (plans[0]) {
    const items = (plans[0].items || []).map((it: any, i: number) => ({ ...it, text: t.plan0.items[i] ?? it.text }))
    plans[0] = { ...plans[0], name: t.plan0.name, text: t.plan0.text, items, price: t.plan0.price }
  }
  await set('pricing', locale, { seo: { ...p.seo, description: t.pricingSeo }, lead: t.pricingLead, plans, formLead: t.formLead })
  console.log(`${locale}: settings, catalogue, course bacc-en, home, pricing updated`)
}
process.exit(0)
