import "dotenv/config";
import { env } from "@/env";
import { db } from "../src/server/db";
import { articles, categories, users } from "../src/server/db/schema";

async function developmentSeed() {
  const usersData = Array.from({ length: 100 }).map((_, i) => ({
    name: `User ${i + 1}`,
    email: `user${i + 1}@example.com`,
    createdAt: new Date(Date.now() + i),
  }));
  const u = await db
    .insert(users)
    .values(usersData)
    .returning({ id: users.id });
  console.log("Seeded " + u.length + " users");

  const categoriesData = Array.from({ length: 250 }).map((_, i) => ({
    name: `Kategorie ${i + 1}`,
    slug: `Kategorie-${i + 1}`,
    createdAt: new Date(Date.now() + i),
  }));
  const c = await db.insert(categories).values(categoriesData).returning({
    id: categories.id,
  });
  console.log("Seeded " + c.length + " categories");

  const articlesData = Array.from({ length: 500 }).map((_, i) => ({
    title: `Artikel ${i + 1}`,
    slug: `Artikel-${i + 1}`,
    createdAt: new Date(Date.now() + i * 5),
    published: true,
  }));
  const a = await db
    .insert(articles)
    .values(articlesData)
    .returning({ id: articles.id });
  console.log("Seeded " + a.length + " articles");
}

async function productionSeed() {
  const user = await db.query.users.findFirst();
  if (user) {
    console.log("Skipped seeding, user already exists");
    return;
  }
  const initialUser = {
    name: "Admin",
    email: "payblot@gmail.com",
    role: 7,
  };
  await db.insert(users).values(initialUser);
  console.log("Seeded user");
}

async function init() {
  try {
    if (env.NODE_ENV === "development") await developmentSeed();
    else if (env.NODE_ENV === "production") await productionSeed();
    else
      console.log(
        "Skipped seeding, NODE_ENV is not set to development or production",
      );
  } catch (error) {
    console.error(error);
  } finally {
    process.exit();
  }
}

init();
