/**
 * Seed E2E — creates an isolated tenant for end-to-end tests so they never touch
 * the demo "Atlas Gestion" data nor real customer tenants.
 *
 * Usage:
 *   - Local:  npx ts-node prisma/seed-e2e.ts
 *   - Prod:   DATABASE_URL=$NEON_URL npx ts-node prisma/seed-e2e.ts
 *
 * Output (printed last line, JSON):
 *   { "tenantId": "...", "syndicEmail": "...", "syndicPassword": "..." }
 *
 * Then point the E2E suite at it:
 *   E2E_TENANT_ID=<tenantId> E2E_USERS_JSON='{"SYNDIC":{"email":"...","password":"..."}}' npm run e2e:prod
 *
 * Idempotent: re-runs are safe — uses upsert on (companyName, contactEmail) markers.
 */
import { PrismaClient, RoleCode } from '@prisma/client'
import * as bcrypt from 'bcrypt'

const prisma = new PrismaClient()

const E2E_MARKER = 'E2E-isolated'

async function ensureRole(code: RoleCode, label: string) {
  return prisma.role.upsert({
    where: { code },
    update: { label },
    create: { code, label },
  })
}

async function main() {
  console.log('🌱 Seeding E2E isolated tenant...')

  // Ensure all roles exist (no-op if seed.ts already ran)
  await ensureRole('SUPERADMIN', 'Super Administrateur')
  const syndicRole = await ensureRole('SYNDIC', 'Syndic / Gestionnaire')

  // Reuse or create the BASE plan (no upsert — seed.ts owns this)
  const basePlan = await prisma.plan.findFirst({ where: { code: 'BASE' } })
  if (!basePlan) {
    throw new Error('BASE plan not found — run `npm run db:seed` first to bootstrap roles + plans.')
  }

  // Tenant: marker in companyName so we never collide with real cabinets
  const companyName = `${E2E_MARKER} — automated test tenant`
  const contactEmail = 'e2e-tenant@syndiclub.test'
  let tenant = await prisma.tenant.findFirst({ where: { contactEmail } })
  if (!tenant) {
    tenant = await prisma.tenant.create({
      data: {
        companyName,
        contactEmail,
        city: 'Casablanca',
        country: 'MA',
        planId: basePlan.id,
        status: 'ACTIVE',
      },
    })
  }

  // Syndic user dedicated to this E2E tenant
  const syndicEmail = 'e2e-syndic@syndiclub.test'
  const syndicPassword = process.env.E2E_SYNDIC_PASSWORD ?? `E2E-Syndic-${Date.now().toString(36)}`
  const passwordHash = await bcrypt.hash(syndicPassword, 10)

  const syndicUser = await prisma.user.upsert({
    where: { email: syndicEmail },
    update: { passwordHash }, // rotate password each run if env var changes
    create: {
      email: syndicEmail,
      passwordHash,
      firstName: 'E2E',
      lastName: 'Syndic',
      language: 'fr',
    },
  })

  // Bind role + tenant
  const existingRole = await prisma.userRole.findFirst({
    where: { userId: syndicUser.id, roleId: syndicRole.id, tenantId: tenant.id },
  })
  if (!existingRole) {
    await prisma.userRole.create({
      data: { userId: syndicUser.id, roleId: syndicRole.id, tenantId: tenant.id },
    })
  }

  console.log('✅ E2E tenant ready')
  console.log(JSON.stringify({
    tenantId: tenant.id,
    syndicEmail,
    syndicPassword,
    note: 'Save the password now — it is hashed in the DB.',
  }))
}

main()
  .catch((e) => {
    console.error('❌ Seed E2E failed:', e)
    process.exit(1)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
