/**
 * Seeds a runnable demo: people + projects via the Workamajig mock sync,
 * then skills, interests, case studies, showcase, education and history.
 * Run: npm run db:seed   (idempotent – safe to re-run)
 */
import "dotenv/config";
import { eq, like } from "drizzle-orm";
import { db, people, skills, personSkills, projects, caseStudies, showcaseItems, educationResources, historyEvents } from "./index";
import { MockWorkamajig } from "../lib/workamajig/mock";
import { syncWorkamajig } from "../lib/workamajig/sync";

const skillCatalog: Record<string, string> = {
  "Art Direction": "craft", "Copywriting": "craft", "Brand Strategy": "craft", "UX Design": "craft", "UI Design": "craft",
  "User Research": "craft", "Front-end Development": "craft", "Back-end Development": "craft", "Full-stack Development": "craft", "Mobile Development": "craft",
  "Analytics": "craft", "Reporting": "craft", "CRO / Experimentation": "craft", "Media Planning": "craft", "Paid Social": "craft",
  "Social Strategy": "craft", "Community Management": "craft", "Video Production": "craft", "Directing": "craft", "Motion Design": "craft",
  "Photography": "craft", "Packaging Design": "craft", "Account Management": "craft", "Pitching": "craft", "Workshop Facilitation": "craft",
  "Accessibility": "craft", "Tone of Voice": "craft", "Experiential": "craft",
  "Figma": "tool", "React": "tool", "Next.js": "tool", "WordPress": "tool", "React Native": "tool", "GA4": "tool", "Looker Studio": "tool",
  "Adobe Premiere": "tool", "After Effects": "tool", "Cinema 4D": "tool", "Optimizely": "tool", "Meta Ads": "tool", "TikTok": "tool", "Webflow": "tool",
  "Irish (Gaeilge)": "language", "Spanish": "language", "French": "language", "Portuguese": "language", "Mandarin": "language", "Japanese": "language",
};

type Extras = { skills: [string, number][]; interests: string[]; bio: string; started: string };
const extras: Record<string, Extras> = {
  "aoife.byrne": { skills: [["Art Direction", 5], ["Pitching", 5], ["Brand Strategy", 4], ["Workshop Facilitation", 4], ["Irish (Gaeilge)", 4]], interests: ["sea swimming", "typography", "GAA"], bio: "Leads the Dublin creative department. Believes the best ideas are the ones that make a client slightly nervous.", started: "2014-03-01" },
  "declan.murphy": { skills: [["Art Direction", 5], ["Packaging Design", 4], ["Photography", 3], ["Figma", 4]], interests: ["cycling", "vinyl", "cooking"], bio: "Art director with a soft spot for print, packaging and anything you can hold in your hand.", started: "2018-09-10" },
  "siobhan.walsh": { skills: [["UX Design", 5], ["Accessibility", 5], ["Figma", 5], ["User Research", 4], ["Workshop Facilitation", 4]], interests: ["hillwalking", "board games", "pottery"], bio: "Runs UX across both offices. Obsessed with journeys that feel effortless and accessible to everyone.", started: "2016-05-16" },
  "cian.oreilly": { skills: [["Front-end Development", 5], ["Back-end Development", 5], ["Next.js", 5], ["React", 5], ["WordPress", 4], ["Accessibility", 4]], interests: ["trail running", "synths", "open source"], bio: "Lead developer. Ships fast, tests properly, and has strong opinions about build tooling.", started: "2017-01-09" },
  "niamh.kelly": { skills: [["Front-end Development", 4], ["React", 4], ["Webflow", 4], ["Motion Design", 2], ["UI Design", 3]], interests: ["climbing", "illustration", "film photography"], bio: "Front-end developer who cares about the last 10% – motion, polish and performance.", started: "2021-06-01" },
  "rory.fitzgerald": { skills: [["Analytics", 5], ["GA4", 5], ["Looker Studio", 4], ["Reporting", 4], ["CRO / Experimentation", 3]], interests: ["chess", "Formula 1", "sourdough"], bio: "Turns data into decisions. Runs measurement for Dublin clients and mentors the analytics grads.", started: "2019-02-04" },
  "grace.dunne": { skills: [["Brand Strategy", 5], ["Tone of Voice", 5], ["Workshop Facilitation", 5], ["Pitching", 4], ["User Research", 3]], interests: ["theatre", "gardening", "podcasts"], bio: "Brand strategist. Finds the emotional truth a brand can own, then helps everyone stay honest about it.", started: "2015-11-02" },
  "oisin.nolan": { skills: [["Account Management", 5], ["Pitching", 5], ["Media Planning", 3]], interests: ["rugby", "sailing", "history"], bio: "Account director for transport and public sector clients. Calm in a crisis, mostly.", started: "2013-08-19" },
  "maya.rodriguez": { skills: [["Art Direction", 5], ["Pitching", 5], ["Brand Strategy", 4], ["Experiential", 4], ["Spanish", 5]], interests: ["salsa", "ceramics", "road trips"], bio: "Executive Creative Director, Boston. Champions work that moves people first and wins awards second.", started: "2011-04-11" },
  "jordan.blake": { skills: [["Copywriting", 5], ["Tone of Voice", 5], ["Social Strategy", 3], ["Pitching", 3]], interests: ["stand-up comedy", "crosswords", "hiking"], bio: "Senior copywriter. Writes headlines, manifestos and the occasional ransom-note-style brief.", started: "2019-10-07" },
  "priya.natarajan": { skills: [["User Research", 5], ["UX Design", 4], ["Workshop Facilitation", 4], ["Accessibility", 4], ["Reporting", 3]], interests: ["yoga", "bird watching", "sci-fi"], bio: "Leads user research. Has interviewed patients, students, fans and fishermen – and remembers all of them.", started: "2020-02-03" },
  "marcus.chen": { skills: [["Full-stack Development", 5], ["React Native", 5], ["Mobile Development", 5], ["React", 4], ["Back-end Development", 4], ["Mandarin", 5]], interests: ["basketball", "mechanical keyboards", "ramen"], bio: "Full-stack developer building products, prototypes and the odd SXSW game.", started: "2020-09-14" },
  "hannah.goldberg": { skills: [["Analytics", 5], ["CRO / Experimentation", 5], ["Optimizely", 5], ["Reporting", 5], ["GA4", 4]], interests: ["marathons", "jazz", "puzzles"], bio: "Director of Analytics. Runs experimentation programmes and makes dashboards people actually open.", started: "2016-07-18" },
  "luis.ortega": { skills: [["Brand Strategy", 4], ["User Research", 3], ["Pitching", 4], ["Spanish", 5], ["Portuguese", 4]], interests: ["football", "travel", "documentaries"], bio: "Brand planner who lives in the space between insight and idea.", started: "2022-01-10" },
  "emily.sato": { skills: [["Social Strategy", 5], ["Paid Social", 5], ["Community Management", 4], ["TikTok", 5], ["Meta Ads", 4], ["Japanese", 4]], interests: ["surfing", "K-dramas", "matcha"], bio: "Social media director. If it's trending, she saw it three days ago.", started: "2018-03-05" },
  "tom.whelan": { skills: [["Video Production", 5], ["Directing", 5], ["Adobe Premiere", 5], ["Photography", 4], ["Experiential", 3]], interests: ["sailing", "vintage cameras", "fishing"], bio: "Heads up CP Studios. Director, editor and occasional drone pilot.", started: "2012-06-04" },
  "fiona.lynch": { skills: [["Media Planning", 5], ["Paid Social", 4], ["Analytics", 3], ["Reporting", 3]], interests: ["horse riding", "wine", "true crime"], bio: "Media director. Plans, buys and optimises across Ireland and the UK.", started: "2015-04-13" },
  "sam.okafor": { skills: [["Motion Design", 5], ["After Effects", 5], ["Cinema 4D", 4], ["UI Design", 3], ["French", 3]], interests: ["skateboarding", "anime", "music production"], bio: "Motion designer. Makes the static things move and the moving things sing.", started: "2021-11-01" },
};

const personByHandle = (h: string) => db.query.people.findFirst({ where: like(people.email, `${h}@%`) });

async function main() {
  console.log("→ Syncing people & projects from Workamajig (mock)…");
  console.log("  ", await syncWorkamajig(new MockWorkamajig()));

  console.log("→ Skills…");
  for (const [name, category] of Object.entries(skillCatalog)) {
    await db.insert(skills).values({ name, category }).onConflictDoUpdate({ target: skills.name, set: { category } });
  }

  console.log("→ Profile extras…");
  for (const [handle, x] of Object.entries(extras)) {
    const person = await personByHandle(handle);
    if (!person) continue;
    await db.update(people).set({
      bio: x.bio, interests: x.interests, startedAt: new Date(x.started),
      linkedinUrl: `https://www.linkedin.com/in/${handle.replace(".", "-")}`,
      photoUrl: `https://api.dicebear.com/9.x/notionists/svg?seed=${encodeURIComponent(handle)}&backgroundColor=e02d00,111111,f4f4f0`,
    }).where(eq(people.id, person.id));
    for (const [skillName, level] of x.skills) {
      const skill = await db.query.skills.findFirst({ where: eq(skills.name, skillName) });
      if (!skill) continue;
      await db.insert(personSkills).values({ personId: person.id, skillId: skill.id, level }).onConflictDoUpdate({ target: [personSkills.personId, personSkills.skillId], set: { level } });
    }
  }

  console.log("→ Case studies…");
  const studies = [
    { slug: "bus-eireann-electrify", number: "BE-2401", title: "Let TFI Electrify Your Bus Journey", clientName: "Bus Éireann", vertical: "Travel & Tourism", year: 2026, tags: ["Campaign", "Video", "OOH", "Social"],
      summary: "Launching Ireland's electric fleet by turning a quiet bus into the loudest thing on the road.",
      challenge: "Electric buses are better for everyone, but 'quieter and cleaner' is a rational message in an emotional category. We needed people to feel the change, not just read about it.",
      approach: "We built the campaign around the moment of silence – the sound a new bus doesn't make. Film, OOH and on-bus experience all played with that absence, while social invited commuters to soundtrack their own journeys.",
      results: "Awareness of the electric fleet more than doubled in launch towns, and the hero film became Bus Éireann's most-shared piece of content to date." },
    { slug: "gortons-sxsw", number: "GO-2301", title: "The Gorton's Fisherman goes to SXSW", clientName: "Gorton's", vertical: "CPG & Retail", year: 2026, tags: ["Experiential", "Social", "Game"],
      summary: "A 175-year-old fisherman walks into a tech festival…",
      challenge: "Gorton's needed cultural relevance with a younger audience who had never bought frozen fish – unless someone gave them a reason to smile.",
      approach: "We put the Fisherman at the centre of an interactive, slightly absurd installation and a playable browser game, with a live social team turning every reaction into content.",
      results: "Over 40,000 game plays in four days and the brand's highest-ever week of organic social engagement." },
    { slug: "expedia-cruises-brand-platform", number: "EX-2401", title: "Expedia Cruises: Set Sail on Something Bigger", clientName: "Expedia Cruises", vertical: "Travel & Tourism", year: 2025, tags: ["Brand", "Strategy", "Campaign"],
      summary: "A new brand platform that reframed cruising from a holiday you book to a life you get to live.",
      challenge: "Cruise marketing all looks the same: pools, buffets, sunsets. Expedia Cruises needed a platform with an emotional point of view.",
      approach: "Research uncovered that first-time cruisers weren't buying a holiday – they were giving themselves permission. The platform built on that feeling across North America.",
      results: "Lifted consideration among first-time cruisers and gave franchisees a platform they actually wanted to use." },
    { slug: "seva-onboarding", number: "SE-2401", title: "Seva: Onboarding that feels like care", clientName: "Seva", vertical: "Health", year: 2026, tags: ["Product", "UX", "Research", "Development"],
      summary: "Redesigning patient onboarding so the first five minutes feel like being looked after.",
      challenge: "Drop-off in the first session was high and the clinical team couldn't see why.",
      approach: "Research with patients and clinicians, a rebuilt onboarding flow in React Native, and analytics instrumentation so the team could watch what changed.",
      results: "First-session completion rose sharply and the clinician dashboard now drives weekly product decisions." },
  ];
  for (const { number, ...cs } of studies) {
    const project = await db.query.projects.findFirst({ where: eq(projects.number, number) });
    const values = { ...cs, projectId: project?.id ?? null };
    await db.insert(caseStudies).values(values).onConflictDoUpdate({ target: caseStudies.slug, set: values });
  }

  console.log("→ Showcase…");
  const showcase = [
    { slug: "fisherman-runner", title: "Fisherman Runner", discipline: "DEVELOPMENT", kind: "GAME", author: "marcus.chen", blurb: "The endless-runner we built for SXSW, now with a leaderboard and a very unfair kraken level.", url: "https://example.com/fisherman-runner" },
    { slug: "soul-meter", title: "Soul Meter", discipline: "ANALYTICS", kind: "EXPERIMENT", author: "hannah.goldberg", blurb: "A prototype emotional-response index: combining survey, dwell and share data into one number clients can rally around.", url: "https://example.com/soul-meter" },
    { slug: "silent-bus-ar", title: "Silent Bus AR filter", discipline: "CREATIVE", kind: "PROTOTYPE", author: "sam.okafor", blurb: "Instagram filter that mutes the world when a bus passes. Built in an afternoon, used by 80k people.", url: "https://example.com/silent-bus" },
    { slug: "journey-map-kit", title: "Journey Map Kit", discipline: "UX", kind: "IDEA", author: "siobhan.walsh", blurb: "A Figma library and workshop script for running journey mapping in 90 minutes with any client team.", url: "https://example.com/journey-kit" },
    { slug: "tone-dial", title: "Tone Dial", discipline: "BRAND", kind: "EXPERIMENT", author: "grace.dunne", blurb: "Slide a dial from 'warm' to 'bold' and watch a brand's copy rewrite itself. A pitch toy that keeps winning rooms.", url: "https://example.com/tone-dial" },
    { slug: "office-sound-map", title: "Dublin Office Sound Map", discipline: "CREATIVE", kind: "IDEA", author: "niamh.kelly", blurb: "Ambient recordings from every corner of Northumberland Road, mapped. Press play, feel the building.", url: "https://example.com/sound-map" },
  ] as const;
  for (const { author, ...s } of showcase) {
    const a = await personByHandle(author);
    const values = { ...s, authorId: a?.id ?? null };
    await db.insert(showcaseItems).values(values).onConflictDoUpdate({ target: showcaseItems.slug, set: values });
  }

  console.log("→ Education…");
  await db.delete(educationResources);
  for (const sp of ["UX", "Dev", "UI", "Videography", "Social Media", "Creative", "Analytics", "Reporting", "User Research"]) {
    await db.insert(educationResources).values([
      { title: `${sp} Library`, description: `Shared Google Drive folder of books, decks, templates and reference material for ${sp}.`, url: "https://drive.google.com/drive/folders/REPLACE_ME", kind: "library", specialty: sp, featured: true },
      { title: `${sp} – Onboarding video`, description: `Start here: a 20-minute walkthrough of how we do ${sp} at CP.`, url: "https://drive.google.com/file/d/REPLACE_ME/view", kind: "video", specialty: sp },
      { title: `${sp} reading list`, description: `Ebooks and long reads the ${sp} team recommends.`, url: "https://drive.google.com/drive/folders/REPLACE_ME", kind: "ebook", specialty: sp },
    ]);
  }

  console.log("→ History…");
  await db.delete(historyEvents);
  const history: [string, string, string, string, string][] = [
    ["1999-01-01", "Connelly Partners is founded", "An independent agency opens its doors in Boston with a simple belief: people buy with their hearts first.", "The founding years", "image"],
    ["2004-06-01", "First national campaign", "The work starts travelling further than the office ever expected.", "The founding years", "image"],
    ["2009-09-01", "CP Studios launches", "In-house film and content production becomes part of how we make things move.", "Building the studio", "video"],
    ["2013-03-01", "Dublin office opens", "59 Northumberland Road, Ballsbridge becomes our European home.", "Going global", "image"],
    ["2016-05-01", "Analytics and experimentation practice", "Measurement joins creative at the table – proof that feelings drive numbers.", "Going global", "image"],
    ["2019-11-01", "Twenty years independent", "Two decades, still owned by the people who work here.", "Going global", "video"],
    ["2021-02-01", "Vancouver joins the map", "A third office, and a team that spans eight time zones.", "Three cities", "image"],
    ["2024-09-01", "Luxe Photography", "A dedicated photography studio for hospitality and luxury clients.", "Three cities", "image"],
    ["2026-07-10", "TFI Electrify launches", "Our quietest, loudest campaign to date.", "Today", "video"],
  ];
  await db.insert(historyEvents).values(history.map(([date, title, body, era, mediaKind], i) => ({ date: new Date(date), title, body, era, mediaKind, sortOrder: i, mediaUrl: `/media/history/${date.slice(0, 4)}.jpg` })));

  console.log("✓ Seed complete");
}

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