// Seed team_members with the two OrthoGlobe founders and the 19-name
// steering committee. Running:
//   pnpm tsx src/lib/db/seed-team.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 SeedMember = {
  slug: string;
  name: string;
  title: string;
  role: "lead" | "committee" | "contributor";
  bio: string;
  country: string;
  institution: string;
  orcidUrl?: string;
  linkedinUrl?: string;
  photo?: string;
  photoAlt?: string;
  position: number;
};

const TEAM: SeedMember[] = [
  {
    slug: "mohamed-imam",
    name: "Prof Mohamed A. Imam",
    title: "Founder & Owner · Clinical Lead · Consultant Shoulder Surgeon",
    role: "lead",
    bio: [
      "Consultant Shoulder & Complex Upper Limb Trauma Surgeon at the Rowley",
      "Bristow Orthopaedic Centre (Ashford & St Peter's NHS Foundation Trust)",
      "and Professor of Digital Health & Surgical Innovation at the University",
      "of East London. MD in shoulder biomechanics, PhD in regenerative",
      "orthopaedics, FRCS (Tr & Orth). 150+ peer-reviewed publications across",
      "shoulder surgery, digital health, and AI-assisted education. Recognised",
      "as a SICOT Pioneer in 2025. Owns OrthoGlobe's clinical direction and",
      "authored the 1,575-SBA OrthoPrep FRCS question bank.",
    ].join(" "),
    country: "United Kingdom",
    institution: "Ashford & St Peter's NHS FT · University of East London",
    orcidUrl: "https://orcid.org/0000-0001-8972-1348",
    photo: "/photos/team/imam.jpg",
    photoAlt: "Professor Mohamed A. Imam",
    position: 1,
  },
  {
    slug: "atef-hassan",
    name: "Dr Atef A. Hassan",
    title: "Chief Operating Officer · Co-Founder",
    role: "lead",
    bio: [
      "Chief Operating Officer and co-founder of OrthoGlobe. Leads platform",
      "engineering, product design, and day-to-day operations across the",
      "collaborative — building the infrastructure that carries OrthoPrep,",
      "ConsentIQ, Atlas, Academy, Store, and the Research portal from",
      "clinical specification to production. Partners closely with Prof Imam",
      "to translate clinical vision into tools members can trust.",
    ].join(" "),
    country: "United Kingdom",
    institution: "OrthoGlobe",
    photo: "/photos/team/atef.jpg",
    photoAlt: "Dr Atef A. Hassan",
    position: 2,
  },
];

const COMMITTEE_NAMES = [
  "Rawad Hammad",
  "Zahra Jaffry",
  "Ahmed Gebaly",
  "Mohamed Abdo Khalafallah",
  "Antony Yiu",
  "Ahmed Negida",
  "Asser Sallam",
  "Isaac John",
  "Hassan Abdalla",
  "Paolo Consigliere",
  "Hazem S. Ghaith",
  "Tony Antonios",
  "Ziad Harb",
  "Ash Evans",
  "Amit Vats",
  "Ali Narvani",
  "Anshul Sobti",
  "Duncan Muir",
  "Parth Patel",
];

function slugify(input: string): string {
  return input
    .toLowerCase()
    .normalize("NFD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/[^a-z0-9\s-]/g, "")
    .trim()
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-");
}

const COMMITTEE: SeedMember[] = COMMITTEE_NAMES.map((name, i) => ({
  slug: slugify(name),
  name,
  title: "Steering committee",
  role: "committee" as const,
  bio: `${name} is a member of the OrthoGlobe international steering committee — a group of practising orthopaedic surgeons and researchers guiding the collaboration's clinical direction, editorial quality, and member review standards.`,
  country: "",
  institution: "",
  position: 100 + i,
}));

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 { teamMembers } = schema;

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

  const all = [...TEAM, ...COMMITTEE];
  let inserted = 0;
  let updated = 0;

  for (const m of all) {
    const existing = await db
      .select({ id: teamMembers.id })
      .from(teamMembers)
      .where(eq(teamMembers.slug, m.slug))
      .limit(1);

    if (existing.length > 0) {
      await db
        .update(teamMembers)
        .set({
          name: m.name,
          title: m.title,
          role: m.role,
          bio: m.bio,
          country: m.country,
          institution: m.institution,
          orcidUrl: m.orcidUrl ?? null,
          linkedinUrl: m.linkedinUrl ?? null,
          photo: m.photo ?? null,
          photoAlt: m.photoAlt ?? null,
          position: m.position,
          status: "active",
          updatedAt: new Date(),
        })
        .where(eq(teamMembers.id, existing[0].id));
      updated += 1;
      console.log(`~ updated ${m.slug}`);
    } else {
      await db.insert(teamMembers).values({
        slug: m.slug,
        name: m.name,
        title: m.title,
        role: m.role,
        bio: m.bio,
        country: m.country,
        institution: m.institution,
        orcidUrl: m.orcidUrl ?? null,
        linkedinUrl: m.linkedinUrl ?? null,
        photo: m.photo ?? null,
        photoAlt: m.photoAlt ?? null,
        position: m.position,
        status: "active",
      });
      inserted += 1;
      console.log(`+ inserted ${m.slug}`);
    }
  }

  console.log(
    `\nDone — ${inserted} inserted, ${updated} updated, ${all.length} total`,
  );
  await sql.end();
}

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