// Seed the Academy LMS with the three real OrthoGlobe Academy courses
// (Chertsey FRCS Course, London Shoulder Masterclass, Advanced MSK for
// Primary Care). Content is ported from the OrthoGlobe Academy HTML.
//
// Running:  SEED_ADMIN_PASSWORD=… pnpm tsx src/lib/db/seed-academy-courses.ts
// Idempotent — re-running upserts by slug.

import { config } from "dotenv";
import path from "node:path";
config({ path: path.resolve(process.cwd(), ".env.local") });

type SeedLesson = {
  slug: string;
  title: string;
  type: "reading" | "video" | "quiz";
  durationMin: number;
  content: string;
  keyPoints?: string[];
};

type SeedModule = {
  title: string;
  lessons: SeedLesson[];
};

type SeedCourse = {
  slug: string;
  title: string;
  level: "Foundation" | "Intermediate" | "Advanced";
  topic: string;
  shortDescription: string;
  description: string;
  outcomes: string[];
  prerequisites: string[];
  instructorName: string;
  instructorTitle: string;
  instructorBio: string;
  modules: SeedModule[];
};

const INSTRUCTOR = {
  name: "Prof Mohamed A. Imam",
  title:
    "Consultant Shoulder & Complex Trauma Surgeon · Professor of Digital Health, UEL",
  bio: "Consultant Shoulder and Complex Trauma Surgeon at the Rowley Bristow Orthopaedic Centre and Professor of Digital Health at the University of East London. 150+ publications and SICOT Pioneer 2025.",
};

const COURSES: SeedCourse[] = [
  {
    slug: "chertsey-frcs-course",
    title: "Chertsey FRCS Course",
    level: "Advanced",
    topic: "Exam preparation",
    shortDescription:
      "The UK's most established FRCS (Tr & Orth) preparation programme — founded by Alan Graham Apley in 1948.",
    description:
      "Step into a legacy of excellence. The Chertsey FRCS Course is possibly the oldest and most respected FRCS preparation programme in the United Kingdom, originally founded by the legendary Alan Graham Apley in 1948. Hosted at the historic Rowley Bristow Orthopaedic Unit, this course has shaped generations of successful orthopaedic surgeons. Our approach combines rigorous academic preparation with practical examination technique. Unlike generic revision courses, the Chertsey FRCS Course is built on nearly eight decades of examination success — our faculty shares the precise language, frameworks, and approaches that examiners expect.",
    outcomes: [
      "Master structured viva responses with examiner-tested frameworks",
      "Refine clinical examination techniques under expert observation",
      "Build confidence through realistic mock examination scenarios",
      "Access insider strategies from faculty who recently passed",
      "Develop rapid recall of essential orthopaedic buzzwords",
      "Practice case-based discussions with immediate feedback",
    ],
    prerequisites: [
      "Orthopaedic trainees preparing for FRCS (Tr & Orth)",
      "ST7/8 trainees in final exam preparation",
      "International trainees seeking UK fellowship examination success",
    ],
    instructorName: INSTRUCTOR.name,
    instructorTitle: INSTRUCTOR.title,
    instructorBio: INSTRUCTOR.bio,
    modules: [
      {
        title: "Day 1 — Core Knowledge Sessions",
        lessons: [
          {
            slug: "structured-viva-techniques",
            title: "Structured viva techniques",
            type: "reading",
            durationMin: 60,
            content:
              "Examiner-tested frameworks for the FRCS Tr & Orth viva: how to open, structure, and close an answer with the language examiners expect.",
            keyPoints: [
              "Open with a clear classification framework",
              "Use buzzwords examiners score against",
              "Close with an evidence-based management plan",
            ],
          },
          {
            slug: "subspecialty-deep-dives",
            title: "Subspecialty deep-dives",
            type: "reading",
            durationMin: 90,
            content:
              "Rapid tour of the high-yield topics across every FRCS subspecialty, mapped to recent exam feedback.",
          },
          {
            slug: "frameworks-and-algorithms",
            title: "Essential frameworks and algorithms",
            type: "reading",
            durationMin: 60,
            content:
              "The structured algorithms and decision trees the examiners expect to hear when the stem turns awkward.",
          },
        ],
      },
      {
        title: "Day 1 — Clinical & Mock Sessions",
        lessons: [
          {
            slug: "clinical-examination-practice",
            title: "Clinical examination practice",
            type: "reading",
            durationMin: 60,
            content:
              "Hands-on refinement of clinical examination routines under expert observation.",
          },
          {
            slug: "case-based-discussions",
            title: "Case-based discussions",
            type: "reading",
            durationMin: 60,
            content:
              "Real-case discussions with immediate feedback — exactly the kind of short-form viva the exam tests.",
          },
          {
            slug: "mock-viva-with-feedback",
            title: "Mock viva with feedback",
            type: "reading",
            durationMin: 60,
            content:
              "Authentic mock viva conditions with scoring and individual feedback from faculty who recently passed.",
          },
        ],
      },
    ],
  },
  {
    slug: "london-shoulder-masterclass",
    title: "London Shoulder Masterclass",
    level: "Advanced",
    topic: "Shoulder",
    shortDescription:
      "Advanced tendon transfer and complex cuff reconstruction — redefining the irreparable. 16–17 July 2026, Central London & Guy's Campus.",
    description:
      "Join an international faculty of world-leading shoulder surgeons for an intensive two-day masterclass on state-of-the-art strategies in shoulder tendon transfers and complex rotator cuff reconstruction. Day 1 delivers high-impact didactic lectures, expert debates, and interactive case discussions. Day 2 offers an immersive cadaveric dissection experience with exceptional faculty-to-participant ratios (2:1 candidate-to-specimen). This isn't a survey course — it's a deep dive into the most challenging reconstructive shoulder problems, with faculty who have pioneered these procedures. 16 CPD credits applied for.",
    outcomes: [
      "Apply evidence-based strategies for complex rotator cuff reconstruction",
      "Evaluate and select management options using structured algorithms",
      "Diagnose and manage scapulothoracic abnormal motion (STAM)",
      "Execute open and arthroscopically assisted tendon transfer techniques",
      "Anticipate and manage intraoperative and postoperative complications",
      "Integrate rehabilitation pathways into surgical planning",
    ],
    prerequisites: [
      "Consultant orthopaedic shoulder and sports surgeons",
      "Senior registrars and fellows with advanced arthroscopic proficiency",
      "Allied health professionals with specialist shoulder interest (Day 1 only)",
    ],
    instructorName: INSTRUCTOR.name,
    instructorTitle: INSTRUCTOR.title,
    instructorBio: INSTRUCTOR.bio,
    modules: [
      {
        title: "Day 1 — Lectures & Expert Discussion",
        lessons: [
          {
            slug: "plenary-lectures-current-evidence",
            title: "Plenary lectures on current evidence",
            type: "reading",
            durationMin: 60,
            content:
              "Current evidence for complex rotator cuff reconstruction from Harvard, Barcelona, Madrid, and UK leaders.",
          },
          {
            slug: "expert-debates-and-video",
            title: "Expert debates and video sessions",
            type: "reading",
            durationMin: 60,
            content:
              "Real-time surgical video analysis and structured expert debates on the cases other courses avoid.",
          },
          {
            slug: "case-panels-complex-tears",
            title: "Case-based panels on complex tears",
            type: "reading",
            durationMin: 60,
            content:
              "Structured decision-making panels on massive, revision, and functionally disabling cuff tears.",
          },
          {
            slug: "rehab-roundtables",
            title: "Rehabilitation roundtables",
            type: "reading",
            durationMin: 45,
            content:
              "Integrating rehabilitation pathways into surgical planning — protocols and pitfalls.",
          },
        ],
      },
      {
        title: "Day 2 — Cadaveric Dissection Lab",
        lessons: [
          {
            slug: "live-demonstration-table",
            title: "Live demonstration table",
            type: "reading",
            durationMin: 60,
            content:
              "Faculty-led demonstration of tendon transfer and reconstruction techniques, step by step.",
          },
          {
            slug: "faculty-led-procedural-stations",
            title: "Faculty-led procedural stations",
            type: "reading",
            durationMin: 180,
            content:
              "Hands-on procedural stations with a 2:1 candidate-to-specimen ratio and real-time troubleshooting.",
          },
          {
            slug: "osats-coaching",
            title: "OSATS-style coaching",
            type: "reading",
            durationMin: 60,
            content:
              "Structured assessment and feedback using OSATS rubrics on each procedural station.",
          },
          {
            slug: "debrief-and-pearls",
            title: "Debrief and pearl consolidation",
            type: "reading",
            durationMin: 45,
            content:
              "Consolidating the day's pearls and linking each station back to clinical decision-making.",
          },
        ],
      },
    ],
  },
  {
    slug: "advanced-msk-primary-care",
    title: "Advanced MSK for Primary Care",
    level: "Intermediate",
    topic: "Musculoskeletal",
    shortDescription:
      "Joint-by-joint mastery for GPs, advanced physiotherapists, and allied health professionals — 6 CPD hours (RCSEd).",
    description:
      "Transform your approach to musculoskeletal care. This intensive one-day course equips advanced primary care practitioners with the knowledge, examination skills, and injection techniques to confidently manage joint pain across every major joint. Led by a multidisciplinary faculty of orthopaedic surgeons, rheumatologists, and specialist physiotherapists, you'll move joint-by-joint through examination, diagnosis, and management — including hands-on injection practice. Most MSK courses teach you what to know. This course teaches you what to do. Every session combines conceptual understanding with practical application, and you leave with injection skills you can use immediately.",
    outcomes: [
      "Perform confident, systematic examination of all major joints",
      "Differentiate inflammatory from mechanical joint pathology",
      "Select appropriate management strategies",
      "Execute joint injection techniques safely and effectively",
      "Understand indications and limitations of orthobiologics including PRP",
      "Apply knowledge immediately in primary care practice",
    ],
    prerequisites: [
      "General practitioners with MSK interest",
      "Advanced physiotherapy practitioners",
      "Osteopaths and chiropractors",
      "Sports physicians and rehabilitation specialists",
    ],
    instructorName: INSTRUCTOR.name,
    instructorTitle: INSTRUCTOR.title,
    instructorBio: INSTRUCTOR.bio,
    modules: [
      {
        title: "Morning — Upper Limb Focus",
        lessons: [
          {
            slug: "shoulder-examination-and-injection",
            title: "Shoulder examination and injection",
            type: "reading",
            durationMin: 60,
            content:
              "Systematic shoulder examination followed by subacromial and glenohumeral injection technique on high-fidelity models.",
          },
          {
            slug: "elbow-and-wrist-assessment",
            title: "Elbow and wrist assessment",
            type: "reading",
            durationMin: 45,
            content:
              "Common elbow and wrist presentations in primary care, with differentiation of inflammatory from mechanical pathology.",
          },
          {
            slug: "hand-conditions-primary-care",
            title: "Hand conditions in primary care",
            type: "reading",
            durationMin: 45,
            content:
              "Trigger finger, de Quervain's, carpal tunnel, and the hand presentations you must not miss.",
          },
        ],
      },
      {
        title: "Afternoon — Spine & Lower Limb",
        lessons: [
          {
            slug: "spinal-assessment-red-flags",
            title: "Spinal assessment red flags",
            type: "reading",
            durationMin: 45,
            content:
              "Red-flag triage for back pain and neurological presentations — what to escalate and when.",
          },
          {
            slug: "hip-and-knee-examination",
            title: "Hip and knee examination",
            type: "reading",
            durationMin: 60,
            content:
              "Structured hip and knee examination with injection technique for knee osteoarthritis.",
          },
          {
            slug: "foot-and-ankle-management",
            title: "Foot and ankle management",
            type: "reading",
            durationMin: 45,
            content:
              "Common foot and ankle presentations with an emphasis on what can be managed in primary care.",
          },
        ],
      },
      {
        title: "Practical — Injection Workshop",
        lessons: [
          {
            slug: "model-based-injection-practice",
            title: "Model-based injection practice",
            type: "reading",
            durationMin: 60,
            content:
              "Hands-on injection practice on high-fidelity joint models, across every major joint covered in the morning.",
          },
          {
            slug: "faculty-supervised-technique",
            title: "Faculty-supervised technique",
            type: "reading",
            durationMin: 45,
            content:
              "Faculty-supervised technique refinement with individual feedback on landmarks, approach, and safety.",
          },
          {
            slug: "prp-demonstration",
            title: "PRP demonstration",
            type: "reading",
            durationMin: 30,
            content:
              "Current evidence for platelet-rich plasma and orthobiologics in primary care MSK practice.",
          },
        ],
      },
    ],
  },
];

async function main() {
  const databaseUrl = process.env.DATABASE_URL;
  if (!databaseUrl) throw new Error("DATABASE_URL not set");

  const postgres = (await import("postgres")).default;
  const { drizzle } = await import("drizzle-orm/postgres-js");
  const { eq } = await import("drizzle-orm");
  const schema = await import("./schema");

  const sql = postgres(databaseUrl, { max: 1 });
  const db = drizzle(sql, { schema });
  const { courses, courseModules, lessons } = schema;

  for (let ci = 0; ci < COURSES.length; ci++) {
    const c = COURSES[ci];
    const existing = await db
      .select({ id: courses.id })
      .from(courses)
      .where(eq(courses.slug, c.slug))
      .limit(1);

    let courseId: string;
    if (existing.length > 0) {
      courseId = existing[0].id;
      await db
        .update(courses)
        .set({
          title: c.title,
          level: c.level,
          topic: c.topic,
          shortDescription: c.shortDescription,
          description: c.description,
          outcomes: c.outcomes,
          prerequisites: c.prerequisites,
          instructorName: c.instructorName,
          instructorTitle: c.instructorTitle,
          instructorBio: c.instructorBio,
          status: "published",
          position: ci,
          publishedAt: new Date(),
          updatedAt: new Date(),
        })
        .where(eq(courses.id, courseId));
      await db.delete(courseModules).where(eq(courseModules.courseId, courseId));
      console.log(`updated course ${c.slug}`);
    } else {
      const [row] = await db
        .insert(courses)
        .values({
          slug: c.slug,
          title: c.title,
          level: c.level,
          topic: c.topic,
          shortDescription: c.shortDescription,
          description: c.description,
          outcomes: c.outcomes,
          prerequisites: c.prerequisites,
          instructorName: c.instructorName,
          instructorTitle: c.instructorTitle,
          instructorBio: c.instructorBio,
          status: "published",
          position: ci,
          publishedAt: new Date(),
        })
        .returning({ id: courses.id });
      courseId = row.id;
      console.log(`seeded course ${c.slug}`);
    }

    for (let mi = 0; mi < c.modules.length; mi++) {
      const m = c.modules[mi];
      const [moduleRow] = await db
        .insert(courseModules)
        .values({ courseId, title: m.title, position: mi })
        .returning({ id: courseModules.id });
      for (let li = 0; li < m.lessons.length; li++) {
        const l = m.lessons[li];
        await db.insert(lessons).values({
          moduleId: moduleRow.id,
          slug: l.slug,
          title: l.title,
          type: l.type,
          durationMin: l.durationMin,
          content: l.content,
          keyPoints: l.keyPoints ?? [],
          position: li,
        });
      }
    }
  }

  await sql.end();
  console.log("academy course seed complete");
  process.exit(0);
}

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