const path = require('node:path');
const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcryptjs');
const dotenv = require('dotenv');

dotenv.config({ path: path.resolve(process.cwd(), '../.env'), quiet: true });
dotenv.config({ path: path.resolve(process.cwd(), '.env'), quiet: true });

const prisma = new PrismaClient();

async function main() {
  const email = 'admin@bizone.id';
  const password = 'ChangeMe123!';
  const passwordHash = await bcrypt.hash(password, 10);
  const adminPermissions = [
    { id: 'campaigns', label: 'Manage Campaigns', icon: 'campaign', description: 'Broadcasts and outbound campaign controls.', values: { view: true, edit: true, delete: true, manage: true } },
    { id: 'analytics', label: 'View Analytics', icon: 'monitoring', description: 'KPI, trends, and performance dashboards.', values: { view: true, edit: null, delete: null, manage: true } },
    { id: 'settings', label: 'Edit Settings', icon: 'settings', description: 'Providers, secrets, and environment-facing settings.', values: { view: true, edit: true, delete: true, manage: true } },
    { id: 'billing', label: 'Billing & Invoices', icon: 'payments', description: 'Plan usage, invoices, and billing visibility.', values: { view: true, edit: null, delete: null, manage: true } },
  ];

  const adminRole = await prisma.role.upsert({
    where: { key: 'admin' },
    update: {
      name: 'Admin',
      summary: 'Full access to all modules, security controls, system configuration, and account-wide actions.',
      badge: 'Active',
      tone: 'primary',
      icon: 'shield_person',
      permissionsJson: adminPermissions,
    },
    create: {
      key: 'admin',
      name: 'Admin',
      summary: 'Full access to all modules, security controls, system configuration, and account-wide actions.',
      badge: 'Active',
      tone: 'primary',
      icon: 'shield_person',
      permissionsJson: adminPermissions,
    },
  });

  const user = await prisma.user.upsert({
    where: { email },
    update: {
      name: 'System Admin',
      passwordHash,
      status: 'active',
      roleId: adminRole.id,
    },
    create: {
      name: 'System Admin',
      email,
      passwordHash,
      status: 'active',
      roleId: adminRole.id,
    },
  });

  console.log(`Seeded admin user: ${user.email}`);
  console.log(`Recommended credentials: ${email} / ${password}`);
}

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