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_${'c'.repeat(64)}`;

const repoMock = {
  listRuns: vi.fn(),
  getRun: vi.fn(),
  listRunSteps: 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_runs_1',
    productId: 'lysnrai',
    userId: 'svc_runs',
    userName: 'Runs 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('runRoutes api key integration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    delete process.env.API_KEY_RATE_LIMIT_CONFIG_JSON;
  });

  it('allows run reads via scoped api key', async () => {
    await seedApiKey(['jobs:read']);
    repoMock.listRuns.mockResolvedValue([{ id: 'run_1', productId: 'lysnrai' }]);

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

    const res = await app.inject({
      method: 'GET',
      url: '/api/runs?limit=10',
      headers: { 'x-api-key': rawApiKey },
    });

    expect(res.statusCode).toBe(200);
    expect(repoMock.listRuns).toHaveBeenCalledWith('lysnrai', { limit: 10 });
  });

  it('rejects product_api keys on run routes', async () => {
    await seedApiKey(['jobs:read'], 'product_api');
    repoMock.listRuns.mockResolvedValue([{ id: 'run_1', productId: 'lysnrai' }]);

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

    const res = await app.inject({
      method: 'GET',
      url: '/api/runs?limit=10',
      headers: { 'x-api-key': rawApiKey },
    });

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