import 'reflect-metadata';
  import { NestFactory } from '@nestjs/core';
  import { Logger } from '@nestjs/common';
  import { AppModule } from '../app.module';
  import { TenantsService } from '../modules/tenants/tenants.service';

  async function run() {
    const logger = new Logger('Seed');
    const app = await NestFactory.createApplicationContext(AppModule, {
      logger: ['log', 'error', 'warn'],
    });
    const tenants = app.get(TenantsService);

    const sample = {
      subdomain: 'demo',
      name: 'Demo Sahakari',
      legalName: 'Demo Cooperative Ltd.',
      adminEmail: 'admin@demo.local',
      adminPassword: 'admin12345',
      adminFullName: 'Demo Admin',
      contactPhone: '9800000000',
    };

    try {
      const existing = await tenants.list();
      if (existing.find((t) => t.subdomain === sample.subdomain)) {
        logger.log('Demo tenant already exists; skipping creation.');
      } else {
        const r = await tenants.create(sample);
        logger.log(`Created tenant: ${r.tenant.subdomain} (admin user id: ${r.adminUserId})`);
      }
      logger.log(`Login as: subdomain=${sample.subdomain}  email=${sample.adminEmail}  password=${sample.adminPassword}`);
    } catch (e) {
      logger.error('Seed failed', (e as Error).stack);
    } finally {
      await app.close();
    }
  }

  void run();
  