import 'dotenv/config';
import { Pool } from 'pg';
import { PrismaPg } from '@prisma/adapter-pg';
import bcrypt from 'bcrypt';
import { DepartmentType, GeoLevel, Position, PrismaClient, Role, UserStatus } from '@prisma/client';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

async function main() {
  console.log('🌱 Starting database seeding...');

  // 1. Seed Geographic Hierarchy Safely (Avoid nested creates on existing state)
  let state = await prisma.state.findFirst({
    where: { name: 'National Capital Region' },
    include: {
      districts: {
        include: {
          townships: true,
        },
      },
    },
  });

  if (!state) {
    state = await prisma.state.create({
      data: {
        name: 'National Capital Region',
        districts: {
          create: {
            name: 'Central District',
            townships: {
              create: {
                name: 'Central Township',
              },
            },
          },
        },
      },
      include: {
        districts: {
          include: {
            townships: true,
          },
        },
      },
    });
  }

  const district = state.districts[0];
  const township = district.townships[0];

  console.log('✅ Base geography ready.');

  // 2. Seed Head Office
  const headOffice = await prisma.office.upsert({
    where: { code: 'HQ-NAT-01' },
    update: {},
    create: {
      code: 'HQ-NAT-01',
      name: 'Attorney General Headquarters',
      level: GeoLevel.NATIONAL,
      department: DepartmentType.ATTORNEY_GENERAL,
      stateId: state.id,
      districtId: district.id,
      townshipId: township.id,
    },
  });

  console.log('✅ Head Office ready.');

  // 3. Seed Basic System Permissions
  const permissions = [
    { name: 'user:create', description: 'Can create new users' },
    { name: 'user:read', description: 'Can view user details' },
    { name: 'user:update', description: 'Can edit user details' },
    { name: 'user:delete', description: 'Can soft delete or disable users' },
    { name: 'document:approve', description: 'Can approve submitted documents' },
  ];

  for (const perm of permissions) {
    await prisma.permission.upsert({
      where: { name: perm.name },
      update: {},
      create: perm,
    });
  }

  console.log('✅ Base permissions ready.');

  // 4. Seed Initial Super Admin
  const defaultPassword = 'SuperAdminPassword123!';
  const hashedPassword = await bcrypt.hash(defaultPassword, 10);

  await prisma.user.upsert({
    where: { email: 'superadmin@system.local' },
    update: {},
    create: {
      employeeCode: 'SA-00001',
      name: 'System Super Admin',
      email: 'superadmin@system.local',
      password: hashedPassword,
      role: Role.SUPER_ADMIN,
      position: Position.CHIEF_ATTORNEY,
      status: UserStatus.ACTIVE,
      officeId: headOffice.id,
      scopeLevel: GeoLevel.NATIONAL,
      scopeStateId: state.id,
    },
  });

  console.log('✅ Super Admin ready.');
  console.log('----------------------------------------------------');
  console.log('🔑 SUPER ADMIN LOGIN CREDENTIALS:');
  console.log(`   Email:    superadmin@system.local`);
  console.log(`   Password: ${defaultPassword}`);
  console.log('----------------------------------------------------');
}

main()
  .catch((e) => {
    console.error('❌ Seeding failed:', e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
    await pool.end(); // Gracefully closes PG pool connection
  });