/**
 * Seeds the database with:
 *  - the 5 default roles from spec §25 and a starter permission set
 *  - the 13 categories from spec §5
 *  - a couple of clearly-labeled DEMO sources (spec §34) for local dev
 *
 * Run with: npm run db:seed
 */
import { PrismaClient } from "@prisma/client";
import { CATEGORIES } from "../config/site";

const prisma = new PrismaClient();

const PERMISSIONS = [
  "articles.view",
  "articles.edit",
  "articles.publish",
  "articles.delete",
  "sources.manage",
  "categories.manage",
  "users.manage",
  "settings.manage",
  "analytics.view",
  "ads.manage",
] as const;

const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
  "Super Admin": PERMISSIONS,
  Admin: PERMISSIONS.filter((p) => p !== "users.manage"),
  Editor: ["articles.view", "articles.edit", "articles.publish", "categories.manage"],
  Author: ["articles.view", "articles.edit"],
  Viewer: ["articles.view", "analytics.view"],
};

async function main() {
  // Permissions
  const permissionRecords = await Promise.all(
    PERMISSIONS.map((key) =>
      prisma.permission.upsert({ where: { key }, update: {}, create: { key } })
    )
  );
  const permissionByKey = new Map(permissionRecords.map((p) => [p.key, p]));

  // Roles
  for (const [name, perms] of Object.entries(ROLE_PERMISSIONS)) {
    const role = await prisma.role.upsert({
      where: { name },
      update: {},
      create: { name, isSystem: true },
    });

    for (const permKey of perms) {
      const permission = permissionByKey.get(permKey);
      if (!permission) continue;
      await prisma.rolePermission.upsert({
        where: { roleId_permissionId: { roleId: role.id, permissionId: permission.id } },
        update: {},
        create: { roleId: role.id, permissionId: permission.id },
      });
    }
  }

  // Categories
  for (const category of CATEGORIES) {
    await prisma.category.upsert({
      where: { slug: category.slug },
      update: { nameAr: category.nameAr },
      create: { slug: category.slug, nameAr: category.nameAr },
    });
  }

  // DEMO sources only — never treated as production feeds.
  await prisma.source.upsert({
    where: { rssUrl: "https://example.com/demo-feed-1.xml" },
    update: {},
    create: {
      name: "[تجريبي] مصدر تجريبي ١",
      website: "https://example.com",
      rssUrl: "https://example.com/demo-feed-1.xml",
      language: "AR",
      isActive: false, // left disabled — admin must knowingly enable it
      isTrusted: false,
      priority: 0,
    },
  });

  console.log("✅ Seed complete: roles, permissions, categories, demo source.");
}

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