import 'dotenv/config';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const prisma = new PrismaClient();

async function main() {
  const email = process.env.INITIAL_ADMIN_EMAIL || 'admin@example.com';
  const password = process.env.INITIAL_ADMIN_PASSWORD || 'ChangeMe2025!!';

  // Create initial admin user
  const existing = await prisma.ccpUser.findUnique({ where: { email } });
  if (!existing) {
    const hashedPassword = await bcrypt.hash(password, 12);
    await prisma.ccpUser.create({
      data: {
        email,
        password: hashedPassword,
        name: 'Admin',
        role: 'SUPER_ADMIN',
      },
    });
    console.log(`Created initial admin user: ${email}`);
  } else {
    console.log(`Admin user already exists: ${email}`);
  }

  // Create default settings
  const defaults: Record<string, unknown> = {
    defaultGitBranch: 'v2',
    instancesBasePath: process.env.INSTANCES_BASE_PATH || 'instances',
  };

  for (const [key, value] of Object.entries(defaults)) {
    await prisma.ccpSetting.upsert({
      where: { key },
      update: {},
      create: { key, value: value as string },
    });
  }
  console.log('Default settings seeded');
}

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