/**
 * Content update, 20 September 2026: the course page gets a «شوف الدروس المجانية» section — the four lessons of
 * Unit 1, each with its own image, each opening in the page itself from YouTube.
 *
 *   docker compose --profile tools run --rm -e NODE_ENV=production  *     -v "D:/OneDrive - DolfTech/Thinkera/marketing/youtube-channel-kit/upload:/app/kit:ro"  *     -v thinkeraacademy_media:/app/media  *     tools npx tsx src/scripts/2026-09-20-free-lessons.ts
 *
 * The media volume matters: without it the images are written inside the throw-away tools container and the site
 * shows broken pictures.
 *
 * 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.
 *
 * Safe to re-run: the images are uploaded once (an image with the same filename is reused), and the lessons are
 * set, not appended.
 */
import fs from 'node:fs'
import path from 'node:path'
import { getPayload } from 'payload'
import config from '@payload-config'

const payload = await getPayload({ config })
type L = 'ar' | 'en'

// the images are the ones the YouTube kit already produces for these very lessons
const KIT = '/app/kit'
const LESSONS = [
  { code: '1-1', file: 'thumbnail_lesson-1-1.png', url: 'https://www.youtube.com/watch?v=nwDk23MQRbA',
    ar: 'تطوّر تقنية المعلومات وتحوّل المجتمع', en: 'Development of IT and Social Transformation' },
  { code: '1-2', file: 'thumbnail_lesson-1-2.png', url: 'https://www.youtube.com/watch?v=_l52_6y88JM',
    ar: 'إزاي بيشتغل الذكاء الاصطناعي', en: 'How AI Works' },
  { code: '1-3', file: 'thumbnail_lesson-1-3.png', url: 'https://www.youtube.com/watch?v=6Lj2w6uL7AQ',
    ar: 'الذكاء الاصطناعي في حياتنا وفي الصناعة', en: 'AI in Daily Life and Industry' },
  { code: '1-4', file: 'thumbnail_lesson-1-4.png', url: 'https://www.youtube.com/watch?v=LXBYiZsMp3Y',
    ar: 'القضايا الأخلاقية في الذكاء الاصطناعي', en: 'Ethical Issues with AI' },
]

/** The media id of an image with this filename, uploading it the first time. */
async function image(file: string, alt: { ar: string; en: string }): Promise<number> {
  const found = await payload.find({ collection: 'media' as never, where: { filename: { equals: file } }, depth: 0, limit: 1 })
  if (found.docs.length) return (found.docs[0] as any).id
  const created = (await payload.create({
    collection: 'media' as never,
    locale: 'ar',
    data: { alt: alt.ar } as never,
    filePath: path.join(KIT, file),
  })) as any
  await payload.update({ collection: 'media' as never, id: created.id, locale: 'en', data: { alt: alt.en } as never })
  console.log('uploaded', file, '→', created.id)
  return created.id
}

const rows: any[] = []
for (const l of LESSONS) {
  rows.push({ code: l.code, videoUrl: l.url, poster: await image(l.file, { ar: `الدرس ${l.code}`, en: `Lesson ${l.code}` }) })
}

const found = await payload.find({ collection: 'courses' as never, where: { slug: { equals: 'bacc-en' } }, depth: 0, limit: 1 })
const course = found.docs[0] as any
if (!course) throw new Error('the course bacc-en is not there')
fs.writeFileSync(
  path.join(process.cwd(), 'src/scripts/backup-2026-09-20-course.json'),
  JSON.stringify({ ar: course, en: await payload.findByID({ collection: 'courses' as never, id: course.id, locale: 'en', depth: 0 }) }, null, 2),
)

// Arabic first, which creates the rows; then English on those same row ids, so the Arabic titles stay.
// (An update that leaves the ids out replaces the rows, and every translation on them goes with it.)
const arabic = (await payload.update({
  collection: 'courses' as never,
  id: course.id,
  locale: 'ar',
  data: { freeLessons: rows.map((r, i) => ({ ...r, title: LESSONS[i].ar })) } as never,
})) as any
await payload.update({
  collection: 'courses' as never,
  id: course.id,
  locale: 'en',
  data: {
    freeLessons: (arabic.freeLessons as any[]).map((row, i) => ({ ...rows[i], id: row.id, title: LESSONS[i].en })),
  } as never,
})
console.log('course bacc-en: four free lessons set')

// the section's own heading and text, and the word on the play button
const labels: Record<L, { freeLessons: string; freeLessonsNote: string; watch: string }> = {
  ar: {
    freeLessons: 'شوف الدروس المجانية',
    freeLessonsNote: 'الوحدة الأولى كلها مجاناً: أربع دروس كاملة بالعامية المصرية وترجمة نصية. اتفرّج هنا على طول، من غير تسجيل.',
    watch: 'شغّل الدرس',
  },
  en: {
    freeLessons: 'Watch the free lessons',
    freeLessonsNote: 'The whole of Unit 1 is free: four full lessons in Egyptian Arabic with subtitles. Watch them here, no sign-up needed.',
    watch: 'Play the lesson',
  },
}
for (const locale of ['ar', 'en'] as L[]) {
  const cat = (await payload.findGlobal({ slug: 'catalogue' as never, locale, depth: 0 })) as any
  await payload.updateGlobal({
    slug: 'catalogue' as never,
    locale,
    data: { labels: { ...(cat.labels || {}), ...labels[locale] } } as never,
  })
}
console.log('catalogue labels set')
process.exit(0)
