import { LeiValidationService } from '@/core/nostro-vostro/lei-validation.service';
import { DbisError } from '@/shared/types';

describe('LeiValidationService', () => {
  const validLei = '5493001KJTIIGC8Y1R35';
  const originalFetch = global.fetch;
  const originalRequireRegistryValidation = process.env.DBIS_REQUIRE_LEI_REGISTRY_VALIDATION;
  const originalAllowFormatOnlyFallback = process.env.DBIS_ALLOW_LEI_FORMAT_ONLY_FALLBACK;

  beforeEach(() => {
    process.env.DBIS_REQUIRE_LEI_REGISTRY_VALIDATION = 'true';
    process.env.DBIS_ALLOW_LEI_FORMAT_ONLY_FALLBACK = 'false';
  });

  afterEach(() => {
    global.fetch = originalFetch;
    process.env.DBIS_REQUIRE_LEI_REGISTRY_VALIDATION = originalRequireRegistryValidation;
    process.env.DBIS_ALLOW_LEI_FORMAT_ONLY_FALLBACK = originalAllowFormatOnlyFallback;
    jest.restoreAllMocks();
  });

  it('rejects malformed LEIs before registry lookup', async () => {
    const service = new LeiValidationService();

    await expect(
      service.validateRegistrationCandidate({
        lei: 'INVALID-LEI',
        institutionName: 'Central Bank of Example',
        country: 'US',
      })
    ).rejects.toBeInstanceOf(DbisError);
  });

  it('accepts issued active LEIs whose legal name and country match the request', async () => {
    global.fetch = jest.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({
        data: {
          id: validLei,
          attributes: {
            entity: {
              legalName: { name: 'Central Bank of Example' },
              legalAddress: { country: 'US' },
              status: 'ACTIVE',
            },
            registration: {
              status: 'ISSUED',
              initialRegistrationDate: '2020-01-01T00:00:00Z',
              nextRenewalDate: '2027-01-01T00:00:00Z',
              managingLou: 'TEST-LOU',
            },
          },
        },
      }),
    }) as typeof fetch;

    const service = new LeiValidationService();
    const result = await service.validateRegistrationCandidate({
      lei: validLei,
      institutionName: 'Central Bank of Example',
      country: 'US',
    });

    expect(result.registryValidated).toBe(true);
    expect(result.legalName).toBe('Central Bank of Example');
    expect(result.legalCountry).toBe('US');
    expect(result.source).toBe('gleif');
  });

  it('rejects registration when the LEI legal name does not match', async () => {
    global.fetch = jest.fn().mockResolvedValue({
      ok: true,
      status: 200,
      json: async () => ({
        data: {
          id: validLei,
          attributes: {
            entity: {
              legalName: { name: 'Different Legal Name Ltd' },
              legalAddress: { country: 'US' },
              status: 'ACTIVE',
            },
            registration: {
              status: 'ISSUED',
            },
          },
        },
      }),
    }) as typeof fetch;

    const service = new LeiValidationService();

    await expect(
      service.validateRegistrationCandidate({
        lei: validLei,
        institutionName: 'Central Bank of Example',
        country: 'US',
      })
    ).rejects.toBeInstanceOf(DbisError);
  });
});
