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

const repoMock = {
  createExportJob: vi.fn(),
  listExportJobs: vi.fn(),
  getExportJob: 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_exports_1',
    productId: 'lysnrai',
    userId: 'svc_exports',
    userName: 'Export 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('exportRoutes api key integration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    delete process.env.API_KEY_RATE_LIMIT_CONFIG_JSON;
  });

  it('allows export reads via service_api keys', async () => {
    await seedApiKey(['exports:read'], 'service_api');
    repoMock.listExportJobs.mockResolvedValue([{ id: 'exp_1', productId: 'lysnrai' }]);

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

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

    expect(res.statusCode).toBe(200);
    expect(repoMock.listExportJobs).toHaveBeenCalledWith('lysnrai', 20);
  });

  it('rejects product_api keys on export routes', async () => {
    await seedApiKey(['exports:read'], 'product_api');

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

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

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