import { Prisma, PrismaClient } from '@prisma/client';
import {
  DEFAULT_PRODUCT_ID,
  DEFAULT_PRODUCT_NAME,
  buildAppDataSeed,
  buildDefaultProjects,
} from './seed-data';

const prisma = new PrismaClient();

async function clearRelationalBusinessData() {
  await prisma.$transaction([
    prisma.comment.deleteMany(),
    prisma.taskWatcher.deleteMany(),
    prisma.task.deleteMany(),
    prisma.sprint.deleteMany(),
    prisma.projectMember.deleteMany(),
    prisma.requirement.deleteMany(),
    prisma.version.deleteMany(),
    prisma.project.deleteMany(),
    prisma.product.deleteMany(),
  ]);
}

async function seedAppData() {
  const entries = buildAppDataSeed();

  for (const entry of entries) {
    const value = entry.value as Prisma.InputJsonValue;
    await prisma.appData.upsert({
      where: { key: entry.key },
      update: { value },
      create: { key: entry.key, value },
    });
  }

  return entries.length;
}

async function seedRelationalBusinessData() {
  await prisma.product.create({
    data: {
      id: DEFAULT_PRODUCT_ID,
      name: DEFAULT_PRODUCT_NAME,
      description: '',
    },
  });

  await prisma.project.createMany({
    data: buildDefaultProjects().map((project) => ({
      id: project.id,
      productId: DEFAULT_PRODUCT_ID,
      name: project.name,
      description: project.description,
    })),
  });
}

async function main() {
  await clearRelationalBusinessData();
  await seedRelationalBusinessData();
  const count = await seedAppData();
  console.log(`Seeded ${count} app_data keys with clean branch data.`);
}

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