/**
 * Seeds a fresh database: the first admin account (from SEED_ADMIN_* env
 * vars), the starter category and authors from the content plan, and the
 * blog defaults. Safe to run repeatedly; existing records are left alone.
 *
 *   npm run db:seed
 */
import { PASSWORD_MIN_LENGTH } from "../src/lib/auth/constants";
import { hashPassword } from "../src/lib/auth/password";
import { createScriptClient } from "../scripts/prisma-client";

const db = createScriptClient();

const categories = [
  {
    name: "Privacy & Security",
    slug: "privacy-security",
    description: "Keep your personal number private online, when selling, renting and dating.",
  },
  {
    name: "Business",
    slug: "business",
    description: "Separate work and personal calls, and look professional with a dedicated line.",
  },
  {
    name: "Travel",
    slug: "travel",
    description: "Stay reachable abroad without roaming charges or swapping SIM cards.",
  },
];

const authors = [
  {
    name: "Olivia Reynolds",
    slug: "olivia-reynolds",
    role: "Privacy & Security Writer",
    bio: "Olivia writes about protecting your personal information in everyday life, from online marketplaces to short-term rentals.",
  },
  {
    name: "Andrew Miller",
    slug: "andrew-miller",
    role: "Small Business Editor",
    bio: "Andrew covers communication tools for freelancers and small teams, with a focus on doing more from one phone.",
  },
];

async function main() {
  const email = process.env.SEED_ADMIN_EMAIL?.trim().toLowerCase();
  const password = process.env.SEED_ADMIN_PASSWORD;

  if (email && password) {
    if (password.length < PASSWORD_MIN_LENGTH) {
      throw new Error(`SEED_ADMIN_PASSWORD must be at least ${PASSWORD_MIN_LENGTH} characters.`);
    }
    const existing = await db.adminUser.findUnique({ where: { email } });
    if (existing) {
      console.log(`Admin ${email} already exists; password unchanged.`);
    } else {
      await db.adminUser.create({
        data: {
          email,
          name: process.env.SEED_ADMIN_NAME?.trim() || "Admin",
          role: "ADMIN",
          passwordHash: await hashPassword(password),
        },
      });
      console.log(`Created admin ${email}.`);
    }
  } else {
    console.log("SEED_ADMIN_EMAIL/SEED_ADMIN_PASSWORD not set; skipping the admin account. Use npm run admin:create.");
  }

  for (const category of categories) {
    await db.category.upsert({ where: { slug: category.slug }, create: category, update: {} });
  }
  for (const author of authors) {
    await db.author.upsert({ where: { slug: author.slug }, create: author, update: {} });
  }
  console.log(`Ensured ${categories.length} categories and ${authors.length} authors.`);

  const privacy = await db.category.findUnique({ where: { slug: "privacy-security" } });
  const olivia = await db.author.findUnique({ where: { slug: "olivia-reynolds" } });
  await db.setting.upsert({
    where: { key: "blogDefaults" },
    create: {
      key: "blogDefaults",
      value: { defaultCategoryId: privacy?.id ?? null, defaultAuthorId: olivia?.id ?? null },
    },
    update: {},
  });
  console.log("Ensured blog defaults.");
}

main()
  .catch((error: unknown) => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(() => db.$disconnect());
