import Fastify from 'fastify';
import bcrypt from 'bcryptjs';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryDatastoreProvider } from '@bytelyst/datastore';
import { setProvider } from '../../lib/datastore.js';
import { registerOptionalApiKeyContext } from '../../lib/api-key-auth.js';

const rawApiKey = `wai_${'f'.repeat(64)}`;

const repoMock = {
  listRules: vi.fn(),
  createRule: vi.fn(),
  deleteRule: vi.fn(),
  checkIP: vi.fn(),
};

vi.mock('./repository.js', () => repoMock);

async function seedApiKey(
  scopes: string[],
  tokenType: 'product_api' | 'service_api' = 'service_api'
) {
  const provider = new MemoryDatastoreProvider();
  setProvider(provider);
  const collection = provider.getCollection('api_tokens', '/id');
  await collection.create({
    id: 'tok_ip_rules_1',
    productId: 'lysnrai',
    userId: 'svc_security',
    userName: 'Security Service',
    tokenType,
    environment: 'dev',
    prefix: rawApiKey.slice(0, 12),
    tokenHash: await bcrypt.hash(rawApiKey, 10),
    status: 'active',
    scopes,
    expiresAt: '2099-01-01T00:00:00.000Z',
    lastUsed: null,
  });
}

describe('ipRuleRoutes api key integration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    delete process.env.API_KEY_RATE_LIMIT_CONFIG_JSON;
  });

  it('allows ip rule reads via service_api keys', async () => {
    await seedApiKey(['ip-rules:read'], 'service_api');
    repoMock.listRules.mockResolvedValue([{ id: 'ipr_1', productId: 'lysnrai' }]);

    const { ipRuleRoutes } = await import('./routes.js');
    const app = Fastify();
    await registerOptionalApiKeyContext(app);
    await app.register(ipRuleRoutes, { prefix: '/api' });

    const res = await app.inject({
      method: 'GET',
      url: '/api/ratelimit/ip-rules',
      headers: { 'x-api-key': rawApiKey },
    });

    expect(res.statusCode).toBe(200);
    expect(repoMock.listRules).toHaveBeenCalledWith('lysnrai');
  });

  it('rejects product_api keys on ip rule routes', async () => {
    await seedApiKey(['ip-rules:read'], 'product_api');

    const { ipRuleRoutes } = await import('./routes.js');
    const app = Fastify();
    await registerOptionalApiKeyContext(app);
    await app.register(ipRuleRoutes, { prefix: '/api' });

    const res = await app.inject({
      method: 'GET',
      url: '/api/ratelimit/ip-rules',
      headers: { 'x-api-key': rawApiKey },
    });

    expect(res.statusCode).toBe(403);
    expect(repoMock.listRules).not.toHaveBeenCalled();
  });
});
