import { APP_GUARD } from '@nestjs/core';
import { MODULE_METADATA } from '@nestjs/common/constants';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { RolesGuard } from './auth/roles.guard';

describe('App security configuration', () => {
  function getAppModuleClass() {
    process.env.JWT_SECRET = process.env.JWT_SECRET ?? 'test-secret';
    // eslint-disable-next-line global-require
    return require('./app.module').AppModule as any;
  }

  it('har globala guards i förväntad ordning: Throttler -> Jwt -> Roles', () => {
    const AppModule = getAppModuleClass();
    const providers =
      (Reflect.getMetadata(MODULE_METADATA.PROVIDERS, AppModule) as any[]) ?? [];

    const appGuards = providers
      .filter((p) => p?.provide === APP_GUARD)
      .map((p) => p.useClass);

    expect(appGuards).toEqual([ThrottlerGuard, JwtAuthGuard, RolesGuard]);
  });

  it('har ThrottlerModule registrerad i AppModule imports', () => {
    const AppModule = getAppModuleClass();
    const imports =
      (Reflect.getMetadata(MODULE_METADATA.IMPORTS, AppModule) as any[]) ?? [];

    const hasThrottler = imports.some(
      (entry) => entry?.module === ThrottlerModule,
    );

    expect(hasThrottler).toBe(true);
  });
});
