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

const prisma = new PrismaClient();

async function main() {
  console.log('Setting up horux_despachos database...');

  // Create admin user
  const hash = await bcrypt.hash('Admin12345!', 12);

  const user = await prisma.user.upsert({
    where: { email: 'ivan@horuxfin.com' },
    update: {},
    create: {
      email: 'ivan@horuxfin.com',
      passwordHash: hash,
      nombre: 'Ivan Admin',
    },
  });
  console.log('✅ User created:', user.email);

  // Find or create tenant
  let tenant = await prisma.tenant.findFirst();
  if (!tenant) {
    tenant = await prisma.tenant.create({
      data: {
        nombre: 'Despacho Demo',
        rfc: 'DDE250101AAA',
        plan: 'business',
        databaseName: 'horux_dde250101aaa',
        verticalProfile: 'CONTABLE',
        dbMode: 'MANAGED',
        trialEndsAt: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
      },
    });
    console.log('✅ Tenant created:', tenant.nombre);
  } else {
    console.log('✅ Tenant exists:', tenant.nombre);
  }

  // Create membership
  await prisma.tenantMembership.upsert({
    where: { userId_tenantId: { userId: user.id, tenantId: tenant.id } },
    update: {},
    create: {
      userId: user.id,
      tenantId: tenant.id,
      rolId: 1,
      isOwner: true,
    },
  });
  console.log('✅ Membership created (owner)');

  // Set lastTenantId
  await prisma.user.update({
    where: { id: user.id },
    data: { lastTenantId: tenant.id },
  });

  console.log('\n🎉 Setup complete!');
  console.log('Login: ivan@horuxfin.com / Admin12345!');
  console.log('Tenant:', tenant.nombre, `(${tenant.rfc})`);
}

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