import { prisma } from '../lib/prisma';
import { auth } from '../lib/auth';

async function main() {
  console.log('Start seeding...');

  // 1. Create Roles
  const adminRole = await prisma.userRole.upsert({
    where: { name: 'ADMIN' },
    update: {},
    create: {
      name: 'ADMIN',
      description: 'Administrator with full access',
      permissions: ['*'],
    },
  });

  await prisma.userRole.upsert({
    where: { name: 'PENDIDIK' },
    update: {},
    create: {
      name: 'PENDIDIK',
      description: 'Educator who can create classes and content',
      permissions: ['class:create', 'class:manage', 'content:create', 'assignment:create', 'forum:moderate'],
    },
  });

  await prisma.userRole.upsert({
    where: { name: 'CALON_PENDIDIK' },
    update: {},
    create: {
      name: 'CALON_PENDIDIK',
      description: 'Prospective educator/student',
      permissions: ['class:join', 'content:view', 'assignment:submit', 'forum:participate'],
    },
  });

  await prisma.userRole.upsert({
    where: { name: 'UMUM' },
    update: {},
    create: {
      name: 'UMUM',
      description: 'General user with basic access',
      permissions: ['content:view', 'forum:general'],
    },
  });

  console.log('Roles created/verified.');

  // 2. Create Admin User
  const adminEmail = 'admin@kreativortex.com';
  const adminPassword = 'adminpassword123'; // Change this in production!

  let adminUserId: string;

  const existingUser = await prisma.user.findUnique({
    where: { email: adminEmail },
  });

  if (existingUser) {
    adminUserId = existingUser.id;
  } else {
    console.log('Creating admin user...');
    const res = await auth.api.signUpEmail({
      body: {
        email: adminEmail,
        password: adminPassword,
        name: 'Admin KreatiVortex',
        image: 'https://ui-avatars.com/api/?name=Admin+KV&background=ffd700&color=000',
      },
    });
    adminUserId = res.user.id;
  }

  // 4. Create Admin Profile
  await prisma.userProfile.upsert({
    where: { userId: adminUserId },
    update: {
      roleId: adminRole.id,
    },
    create: {
      userId: adminUserId,
      roleId: adminRole.id,
      bio: 'Administrator of KreatiVortex Platform',
    },
  });

  console.log(`Admin user created with email: ${adminEmail}`);

  // 5. Seed Menus
  const menus = [
    {
      name: { id: 'Teori', en: 'Theory' },
      description: { id: 'Menu pembelajaran teori tari', en: 'Dance theory learning menu' },
      children: [
        'Pengetahuan dasar tari',
        'Unsur utama gerak',
        'Unsur utama pertunjukan tari',
        'Penciptaan tari dan pengambangan diri',
      ],
    },
    {
      name: { id: 'Praktik', en: 'Practice' },
      description: { id: 'Menu pembelajaran praktik tari', en: 'Dance practice learning menu' },
      children: ['Olah Tubuh', 'Imitasi Gerak', 'Gerak Dasar'],
    },
    {
      name: { id: 'Template Makalah', en: 'Paper Template' },
      description: { id: 'Template penyusunan makalah', en: 'Paper composition template' },
      children: [],
    },
    {
      name: { id: 'Tempo', en: 'Tempo' },
      description: { id: 'Latihan tempo gerak', en: 'Movement tempo practice' },
      children: [],
    },
  ];

  // Helper to create slugs
  const slugify = (text: string) =>
    text
      .toLowerCase()
      .replace(/ /g, '-')
      .replace(/[^\w-]+/g, '');

  for (const menuData of menus) {
    const menuSlug = slugify(menuData.name.id);

    // Check if parent menu exists
    let parentMenu = await prisma.menu.findFirst({
      where: {
        slug: menuSlug,
        parentId: null,
      },
    });

    if (!parentMenu) {
      console.log(`Creating menu: ${menuData.name.id} (${menuSlug})`);
      parentMenu = await prisma.menu.create({
        data: {
          name: menuData.name,
          slug: menuSlug,
          description: menuData.description,
          updatedBy: adminUserId,
        },
      });
    } else {
      console.log(`Menu already exists: ${menuData.name.id}`);
    }

    // Create children
    for (const childName of menuData.children) {
      const childNameJson = { id: childName, en: childName };
      const childSlug = slugify(childName);

      const childMenu = await prisma.menu.findFirst({
        where: {
          slug: childSlug,
          parentId: parentMenu.id,
        },
      });

      if (!childMenu) {
        console.log(`Creating sub-menu: ${childName} (${childSlug})`);
        await prisma.menu.create({
          data: {
            name: childNameJson,
            slug: childSlug,
            description: { id: childName, en: childName },
            parentId: parentMenu.id,
            updatedBy: adminUserId,
          },
        });
      }
    }
  }

  console.log('Seeding finished.');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
