import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AlarmIngestionModule } from './modules/alarm-ingestion/alarm-ingestion.module';
import { LampIngestionModule } from './modules/lamp-ingestion/lamp-ingestion.module';
import { AlarmsModule } from './modules/alarms/alarms.module';
import { AuthModule } from './modules/auth/auth.module';
import { CommonModule } from './common/common.module';
import { DashboardModule } from './modules/dashboard/dashboard.module';
import { LampsModule } from './modules/lamps/lamps.module';
import { MapModule } from './modules/map/map.module';
import { PrismaModule } from './modules/prisma/prisma.module';
import { RedisModule } from './modules/redis/redis.module';
import { RegionsModule } from './modules/regions/regions.module';
import { RolesModule } from './modules/roles/roles.module';
import { TenantsModule } from './modules/tenants/tenants.module';
import { UsersModule } from './modules/users/users.module';

/** 与启动时 cwd 无关：先根据入口文件位置找 backend/.env，再回退到 cwd 下常见路径 */
function resolveEnvFilePath(): string | undefined {
  const candidates = [
    join(__dirname, '..', '.env'),
    join(__dirname, '..', '..', '.env'),
    join(process.cwd(), 'backend', '.env'),
    join(process.cwd(), '.env'),
  ];
  return candidates.find((p) => existsSync(p));
}

const resolvedEnvFile = resolveEnvFilePath();

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: resolvedEnvFile ? [resolvedEnvFile] : ['.env'],
    }),
    PrismaModule,
    RedisModule,
    AuthModule,
    CommonModule,
    TenantsModule,
    UsersModule,
    RolesModule,
    RegionsModule,
    LampsModule,
    AlarmsModule,
    DashboardModule,
    MapModule,
    AlarmIngestionModule,
    LampIngestionModule,
  ],
})
export class AppModule {}
