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 = {
  listSubscriptions: vi.fn(),
  createSubscription: vi.fn(),
  getSubscription: vi.fn(),
  updateSubscription: vi.fn(),
  deleteSubscription: vi.fn(),
  listDeliveries: vi.fn(),
};

const dispatcherMock = {
  dispatchEvent: vi.fn(),
};

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

async function seedApiKey(scopes: string[]) {
  const provider = new MemoryDatastoreProvider();
  setProvider(provider);
  const collection = provider.getCollection('api_tokens', '/id');
  await collection.create({
    id: 'tok_webhooks_1',
    productId: 'lysnrai',
    userId: 'svc_webhooks',
    userName: 'Webhook Service',
    tokenType: 'service_api',
    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('webhookRoutes api key integration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('allows subscription listing via scoped api key', async () => {
    await seedApiKey(['webhooks:read']);
    repoMock.listSubscriptions.mockResolvedValue([{ id: 'sub_1', productId: 'lysnrai' }]);

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

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

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

  it('allows subscription creation via scoped api key', async () => {
    await seedApiKey(['webhooks:write']);
    repoMock.createSubscription.mockResolvedValue({
      id: 'sub_1',
      productId: 'lysnrai',
      url: 'https://example.com/hook',
      secret: 'abc',
    });

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

    const res = await app.inject({
      method: 'POST',
      url: '/api/webhooks/subscriptions',
      headers: { 'x-api-key': rawApiKey },
      payload: {
        url: 'https://example.com/hook',
        events: ['user.created'],
        productId: 'other-product-ignored',
      },
    });

    expect(res.statusCode).toBe(200);
    expect(repoMock.createSubscription).toHaveBeenCalledWith(
      expect.objectContaining({
        productId: 'lysnrai',
      }),
      expect.any(String),
      'svc_webhooks'
    );
  });
});
