import { eq, inArray } from "drizzle-orm";
import { db, pool } from "./index.js";
import {
  onboardingEnrollmentsTable,
  onboardingProgramsTable,
  onboardingProgramWeeksTable,
  onboardingWeekActivitiesTable,
  usersTable,
} from "./schema/index.js";

const PROGRAM_TITLE = "WWN 12-Day Onboarding (All Activity Types)";

type SeedActivity = {
  title: string;
  description: string;
  durationMinutes?: number | null;
  type:
    | "VIDEO"
    | "FILE"
    | "RICH_TEXT"
    | "EXTERNAL_LINK"
    | "QUIZ"
    | "CHECKLIST"
    | "SURVEY";
  content: Record<string, unknown> | null;
  isRequired?: boolean;
};

type SeedDay = {
  dayNumber: number;
  title: string;
  description: string;
  activities: SeedActivity[];
};

const days: SeedDay[] = [
  {
    dayNumber: 1,
    title: "Welcome & Orientation",
    description: "Get familiar with WWN and set your goals for the next 12 days.",
    activities: [
      {
        title: "Welcome video",
        description: "A short introduction to the WWN experience.",
        durationMinutes: 6,
        type: "VIDEO",
        content: { url: "https://www.youtube.com/watch?v=ysz5S6PUM-U" },
      },
      {
        title: "Quick start guide",
        description: "Read this before you explore the platform.",
        type: "RICH_TEXT",
        content: {
          html: `<h3>Quick start</h3><ul><li>Complete your profile</li><li>Review community expectations</li><li>Join discussions and introduce yourself</li></ul><p><strong>Tip:</strong> pace yourself — this onboarding unlocks daily.</p>`,
        },
      },
    ],
  },
  {
    dayNumber: 2,
    title: "Community Standards",
    description: "Learn how we keep WWN safe, respectful, and supportive.",
    activities: [
      {
        title: "Community guidelines (PDF)",
        description: "Download and review the guidelines.",
        durationMinutes: 8,
        type: "FILE",
        content: { url: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" },
      },
      {
        title: "Read: UN Women overview",
        description: "External reading to ground our shared mission context.",
        durationMinutes: 6,
        type: "EXTERNAL_LINK",
        content: { url: "https://www.unwomen.org/en" },
      },
      {
        title: "Confirm your commitment",
        description: "A quick checklist to set expectations.",
        durationMinutes: 3,
        type: "CHECKLIST",
        content: {
          value:
            "Checklist:\n- I will be respectful\n- I will protect member privacy\n- I will contribute constructively\n- I will ask questions when unsure",
        },
      },
    ],
  },
  {
    dayNumber: 3,
    title: "Your Profile",
    description: "Set up your profile to get the most out of WWN.",
    activities: [
      {
        title: "Complete your profile checklist",
        description: "Confirm the basics are done so you can participate fully.",
        durationMinutes: 5,
        type: "CHECKLIST",
        content: {
          value:
            "Checklist:\n- Add your location\n- Add a short bio\n- Add your interests\n- Update your notification preferences",
        },
      },
      {
        title: "Profile visibility (short quiz)",
        description: "Quick self-check: what is safe to share?",
        durationMinutes: 4,
        type: "QUIZ",
        content: {
          value:
            "Quiz:\n1) Should you share your full home address? (No)\n2) Should you share your phone number publicly? (No)\n3) What should you do if you see harassment? (Report it)",
        },
      },
    ],
  },
  {
    dayNumber: 4,
    title: "Platform Tour",
    description: "Learn where to find key modules and resources.",
    activities: [
      {
        title: "Platform tour notes",
        description: "A short walkthrough of how to navigate WWN.",
        durationMinutes: 7,
        type: "RICH_TEXT",
        content: {
          html: `<h3>Where things live</h3><ul><li><strong>Dashboard</strong>: your home</li><li><strong>Community</strong>: discussions & events</li><li><strong>Resources</strong>: documents and tools</li></ul><p>Use search to move fast.</p>`,
        },
      },
      {
        title: "Watch: intro to online safety",
        description: "Be mindful of links and shared files.",
        durationMinutes: 5,
        type: "VIDEO",
        content: { url: "https://www.youtube.com/watch?v=jNQXAC9IVRw" },
      },
      {
        title: "Tell us what you want from WWN",
        description: "A simple survey to personalize your experience.",
        durationMinutes: 3,
        type: "SURVEY",
        content: {
          value:
            "Survey:\n- What are your top 2 goals?\n- Which topics are most relevant?\n- What would make WWN a success for you?",
        },
      },
    ],
  },
  {
    dayNumber: 5,
    title: "Financial Foundations",
    description: "Set a baseline for your savings and budgeting habits.",
    activities: [
      {
        title: "Download: budgeting template",
        description: "A starter template you can reuse.",
        durationMinutes: 10,
        type: "FILE",
        content: { url: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" },
      },
      {
        title: "Read: simple budgeting principles",
        description: "Learn a few rules of thumb.",
        durationMinutes: 6,
        type: "EXTERNAL_LINK",
        content: { url: "https://www.investopedia.com/terms/b/budget.asp" },
      },
    ],
  },
  {
    dayNumber: 6,
    title: "SUSU & Savings Culture",
    description: "Understand how group savings works in WWN.",
    activities: [
      {
        title: "SUSU explainer video",
        description: "A short explainer of the SUSU model.",
        durationMinutes: 8,
        type: "VIDEO",
        content: { url: "https://www.youtube.com/watch?v=ysz5S6PUM-U" },
      },
      {
        title: "SUSU participation checklist",
        description: "Be ready before joining a circle.",
        durationMinutes: 4,
        type: "CHECKLIST",
        content: {
          value:
            "Checklist:\n- Understand the contribution amount\n- Know payout order\n- Confirm auto-debit setup\n- Review circle rules",
        },
      },
      {
        title: "SUSU quick quiz",
        description: "Check your understanding.",
        durationMinutes: 3,
        type: "QUIZ",
        content: {
          value:
            "Quiz:\n1) Can you skip contributions? (No)\n2) What happens if you miss? (It affects your standing)\n3) Why do we set rules? (Trust & clarity)",
        },
      },
    ],
  },
  {
    dayNumber: 7,
    title: "Matching Fund",
    description: "Learn how Matching Fund and repayments work.",
    activities: [
      {
        title: "Matching Fund overview",
        description: "What it is, when to use it, and how repayment works.",
        durationMinutes: 6,
        type: "RICH_TEXT",
        content: {
          html: `<h3>Matching Fund</h3><p>This feature supports short-term needs with clear repayment expectations.</p><ul><li>Borrow responsibly</li><li>Repay on time</li><li>Communicate early if you have issues</li></ul>`,
        },
      },
      {
        title: "Read: financial resilience",
        description: "External reading for perspective.",
        durationMinutes: 5,
        type: "EXTERNAL_LINK",
        content: { url: "https://www.oecd.org/financial/education/" },
      },
    ],
  },
  {
    dayNumber: 8,
    title: "Susunomics & Investing",
    description: "Understand the basics of investing and risk.",
    activities: [
      {
        title: "Investing basics video",
        description: "A short introduction to risk and diversification.",
        durationMinutes: 7,
        type: "VIDEO",
        content: { url: "https://www.youtube.com/watch?v=ysz5S6PUM-U" },
      },
      {
        title: "Investor readiness survey",
        description: "Tell us your comfort level with risk.",
        durationMinutes: 4,
        type: "SURVEY",
        content: {
          value:
            "Survey:\n- Your risk tolerance (low/medium/high)\n- Your investing time horizon\n- Your preferred learning format",
        },
      },
      {
        title: "Read: diversification",
        description: "External reading on why diversification matters.",
        durationMinutes: 6,
        type: "EXTERNAL_LINK",
        content: { url: "https://www.investopedia.com/terms/d/diversification.asp" },
      },
    ],
  },
  {
    dayNumber: 9,
    title: "Community Participation",
    description: "Learn how to contribute and find support.",
    activities: [
      {
        title: "How to ask good questions",
        description: "A simple guide to get helpful answers.",
        durationMinutes: 6,
        type: "RICH_TEXT",
        content: {
          html: `<h3>Ask better questions</h3><ul><li>Share context</li><li>Be specific</li><li>Explain what you tried</li></ul><p>This helps members support you faster.</p>`,
        },
      },
      {
        title: "Participation checklist",
        description: "A simple habit checklist.",
        durationMinutes: 4,
        type: "CHECKLIST",
        content: {
          value:
            "Checklist:\n- Introduce yourself\n- Respond to one discussion\n- Save one useful resource\n- Attend or RSVP to one event",
        },
      },
    ],
  },
  {
    dayNumber: 10,
    title: "Policies & Accountability",
    description: "Understand expectations and how we handle issues.",
    activities: [
      {
        title: "Code of conduct (PDF)",
        description: "Review how we keep WWN constructive.",
        durationMinutes: 7,
        type: "FILE",
        content: { url: "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" },
      },
      {
        title: "Short policy quiz",
        description: "Check your understanding of key rules.",
        durationMinutes: 4,
        type: "QUIZ",
        content: {
          value:
            "Quiz:\n1) Is harassment tolerated? (No)\n2) What should you do if you see abuse? (Report)\n3) Should you share private member info? (Never)",
        },
      },
      {
        title: "Policy feedback survey",
        description: "Tell us what policies you want clarified.",
        durationMinutes: 3,
        type: "SURVEY",
        content: {
          value:
            "Survey:\n- Which policy sections are unclear?\n- What examples would help?\n- Any suggestions for improvement?",
        },
      },
    ],
  },
  {
    dayNumber: 11,
    title: "Personal Action Plan",
    description: "Turn what you learned into a practical plan.",
    activities: [
      {
        title: "Action plan worksheet",
        description: "A simple worksheet to capture your next steps.",
        durationMinutes: 10,
        type: "RICH_TEXT",
        content: {
          html: `<h3>Your plan</h3><ol><li>Pick 1 savings goal</li><li>Pick 1 community goal</li><li>Pick 1 learning goal</li></ol><p>Write them down and commit to a date.</p>`,
        },
      },
      {
        title: "Commitment checklist",
        description: "Confirm your plan is realistic and scheduled.",
        durationMinutes: 4,
        type: "CHECKLIST",
        content: {
          value:
            "Checklist:\n- Goals are specific\n- Next action is scheduled\n- You know where to ask for help\n- You will review progress weekly",
        },
      },
    ],
  },
  {
    dayNumber: 12,
    title: "Wrap-Up & Next Steps",
    description: "Finish strong and plan how you’ll stay active in WWN.",
    activities: [
      {
        title: "Final reflection",
        description: "A short reflection to close out onboarding.",
        durationMinutes: 6,
        type: "RICH_TEXT",
        content: {
          html: `<h3>Reflection</h3><ul><li>What did you learn?</li><li>What will you do next?</li><li>Where will you show up consistently?</li></ul>`,
        },
      },
      {
        title: "Share a win (external link)",
        description: "Optional: share your progress with your community.",
        durationMinutes: 3,
        type: "EXTERNAL_LINK",
        content: { url: "https://www.linkedin.com/" },
        isRequired: false,
      },
      {
        title: "Completion quiz",
        description: "A quick final check-in.",
        durationMinutes: 3,
        type: "QUIZ",
        content: {
          value:
            "Quiz:\n1) Can you skip ahead in onboarding? (No)\n2) How often does a new day unlock? (Daily)\n3) What should you do if stuck? (Ask for help)",
        },
      },
    ],
  },
];

async function main() {
  const existing = await db
    .select({ id: onboardingProgramsTable.id })
    .from(onboardingProgramsTable)
    .where(eq(onboardingProgramsTable.title, PROGRAM_TITLE));

  if (existing[0]) {
    const programId = existing[0].id;
    const enrollments = await db
      .select({ userId: onboardingEnrollmentsTable.userId })
      .from(onboardingEnrollmentsTable)
      .where(eq(onboardingEnrollmentsTable.programId, programId));
    const affectedUserIds = Array.from(
      new Set(enrollments.map((row) => row.userId)),
    );

    await db.transaction(async (tx) => {
      if (affectedUserIds.length > 0) {
        await tx
          .delete(onboardingEnrollmentsTable)
          .where(eq(onboardingEnrollmentsTable.programId, programId));
        await tx
          .update(usersTable)
          .set({ onboardingCompletedAt: null })
          .where(inArray(usersTable.id, affectedUserIds));
      }
      await tx
        .delete(onboardingProgramsTable)
        .where(eq(onboardingProgramsTable.id, programId));
    });
  }

  const now = new Date();
  const [program] = await db
    .insert(onboardingProgramsTable)
    .values({
      title: PROGRAM_TITLE,
      description:
        "A 12-day onboarding programme seeded with all supported activity types (video, file, rich text, external links, quiz, checklist, survey).",
      numberOfWeeks: 12,
      durationUnit: "DAY",
      status: "PUBLISHED",
      createdAt: now,
      updatedAt: now,
    })
    .returning();

  const weekRows = await db
    .insert(onboardingProgramWeeksTable)
    .values(
      days.map((day, idx) => ({
        programId: program.id,
        weekNumber: day.dayNumber,
        title: day.title,
        description: day.description,
        sortOrder: idx,
        createdAt: now,
        updatedAt: now,
      })),
    )
    .returning();

  const weekIdByDay = new Map<number, number>();
  for (const row of weekRows) {
    weekIdByDay.set(row.weekNumber, row.id);
  }

  for (const day of days) {
    const weekId = weekIdByDay.get(day.dayNumber);
    if (!weekId) continue;
    await db.insert(onboardingWeekActivitiesTable).values(
      day.activities.map((activity, idx) => ({
        weekId,
        title: activity.title,
        description: activity.description,
        durationMinutes:
          activity.durationMinutes == null ? null : Number(activity.durationMinutes),
        type: activity.type as any,
        content: activity.content,
        sortOrder: idx,
        isRequired: activity.isRequired ?? true,
        createdAt: now,
        updatedAt: now,
      })),
    );
  }

  const weeks = await db
    .select({ id: onboardingProgramWeeksTable.id })
    .from(onboardingProgramWeeksTable)
    .where(eq(onboardingProgramWeeksTable.programId, program.id));

  const weekIds = weeks.map((w) => w.id);
  const activityCount = weekIds.length
    ? await db
        .select({ id: onboardingWeekActivitiesTable.id })
        .from(onboardingWeekActivitiesTable)
        .where(inArray(onboardingWeekActivitiesTable.weekId, weekIds))
    : [];

  console.log(
    `Seeded programme: ${program.title} (id=${program.id}) | days=${weekIds.length} | activities=${activityCount.length}`,
  );
}

main()
  .catch((err) => {
    console.error(err);
    process.exitCode = 1;
  })
  .finally(async () => {
    await pool.end();
  });
