import { Test, TestingModule } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { UnauthorizedException } from '@nestjs/common';
import { InternalController } from './internal.controller';
import { ServiceCredentialValidatorService } from '../common/services/service-credential-validator.service';

describe('InternalController (evict)', () => {
  let controller: InternalController;
  const evict = jest.fn();
  const config: Record<string, unknown> = {
    SERVICE_CREDENTIALS_INTERNAL_SECRET: 'internal-secret-xyz',
  };

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [InternalController],
      providers: [
        { provide: ServiceCredentialValidatorService, useValue: { evict } },
        { provide: ConfigService, useValue: { get: (k: string) => config[k] } },
      ],
    }).compile();
    controller = module.get(InternalController);
  });

  afterEach(() => jest.clearAllMocks());

  it('evicts the prefix when the internal secret matches', () => {
    evict.mockReturnValue(2);
    const res = controller.evict('internal-secret-xyz', {
      prefix: 'pf_sk_live_a1b2c3d4',
    });
    expect(evict).toHaveBeenCalledWith('pf_sk_live_a1b2c3d4');
    expect(res).toEqual({ evicted: 2 });
  });

  it('rejects a wrong/missing internal secret (401) and does not evict', () => {
    expect(() =>
      controller.evict('wrong', { prefix: 'pf_sk_live_a1b2c3d4' }),
    ).toThrow(UnauthorizedException);
    expect(() =>
      controller.evict(undefined as unknown as string, { prefix: 'x' }),
    ).toThrow(UnauthorizedException);
    expect(evict).not.toHaveBeenCalled();
  });

  it('rejects a missing prefix (400-style) without evicting', () => {
    expect(() =>
      controller.evict('internal-secret-xyz', { prefix: '' }),
    ).toThrow();
    expect(evict).not.toHaveBeenCalled();
  });
});
