/* eslint-disable */
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function upsertUsers() {
  const usernames = ['SeedUser_Alpha', 'SeedUser_Beta', 'SeedUser_Gamma', 'SeedUser_Delta'];
  const authors = [];
  for (const username of usernames) {
    const user = await prisma.user.upsert({
      where: { username },
      update: {},
      create: {
        username,
        password: null,
        role: 'CREATOR',
        status: 'ACTIVE',
        avatarUrl: `https://api.dicebear.com/7.x/avataaars/svg?seed=${encodeURIComponent(username)}`,
      },
    });
    authors.push(user);
  }
  return authors;
}

async function upsertTags() {
  const names = ['code', 'seed', 'demo'];
  const tags = [];
  for (const name of names) {
    const tag = await prisma.tag.upsert({
      where: { name },
      update: {},
      create: { name },
    });
    tags.push(tag);
  }
  return tags;
}

async function seedMaterials(authors, tags) {
  const total = 40;
  for (let i = 1; i <= total; i++) {
    const title = `Seed Code #${String(i).padStart(2, '0')}`;
    const existing = await prisma.material.findFirst({ where: { title, type: 'CODE' } });
    if (existing) continue;

    const author = authors[i % authors.length];
    const snippet = `export const seed${i} = () => ${i};`;
    await prisma.material.create({
      data: {
        title,
        description: 'Seeded code snippet for pagination demo.',
        type: 'CODE',
        codeSnippet: snippet,
        language: 'ts',
        authorId: author.id,
        tags: {
          connect: tags.map(t => ({ id: t.id })),
        },
      },
    });
  }
}

async function main() {
  console.log('[SEED] Starting...');
  const authors = await upsertUsers();
  const tags = await upsertTags();
  await seedMaterials(authors, tags);
  const count = await prisma.material.count({ where: { type: 'CODE' } });
  console.log(`[SEED] Done. CODE materials count: ${count}`);
}

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

