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

const repoMock = {
  getMaintenanceConfig: vi.fn(),
  listUpcomingWindows: vi.fn(),
  updateMaintenanceConfig: vi.fn(),
  createWindow: vi.fn(),
  deleteWindow: 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_maintenance_1',
    productId: 'lysnrai',
    userId: 'svc_ops',
    userName: 'Ops 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('maintenanceRoutes api key integration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    delete process.env.API_KEY_RATE_LIMIT_CONFIG_JSON;
  });

  it('allows maintenance reads via service_api keys', async () => {
    await seedApiKey(['maintenance:read'], 'service_api');
    repoMock.getMaintenanceConfig.mockResolvedValue({ mode: 'off', productId: 'lysnrai' });

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

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

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

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

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

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

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