import * as bcrypt from 'bcryptjs';
import { PrismaMariaDb } from '@prisma/adapter-mariadb';
import { PrismaClient, UserRole, UserStatus } from '@prisma/client';

try {
  process.loadEnvFile('.env');
} catch {
  // No .env file: use variables already set in the shell.
}

const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
  throw new Error('DATABASE_URL environment variable is not defined');
}

const adminEmail = 'admin@techcmantix.com';
const adminPassword = '123456';

const prisma = new PrismaClient({
  adapter: new PrismaMariaDb(connectionString),
});

async function main(): Promise<void> {
  const existing = await prisma.user.findUnique({
    where: { email: adminEmail },
  });

  if (existing && existing.role !== UserRole.PLATFORM_ADMIN) {
    throw new Error(`${adminEmail} already belongs to a tenant user.`);
  }

  if (!existing) {
    const passwordHash = await bcrypt.hash(adminPassword, 12);

    await prisma.user.create({
      data: {
        email: adminEmail,
        name: 'Platform Admin',
        role: UserRole.PLATFORM_ADMIN,
        status: UserStatus.ACTIVE,
        passwordHash,
        tenantId: null,
      },
    });

    console.log(`Platform admin created: ${adminEmail}`);
  } else {
    console.log(`Platform admin already exists: ${adminEmail}`);
  }
}

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