import type { Request, Response } from 'express';
import { describe, expect, it, vi } from 'vitest';
import { blockBots } from '../bot-detect';

function createResponse() {
  return {
    status: vi.fn().mockReturnThis(),
    json: vi.fn(),
  } as unknown as Response;
}

describe('blockBots', () => {
  it('blocks anonymous bot user agents', () => {
    const req = {
      headers: {
        'user-agent': 'Mozilla/5.0 HeadlessChrome/123.0.0.0',
      },
    } as Request;
    const res = createResponse();
    const next = vi.fn();

    blockBots(req, res, next);

    expect(res.status).toHaveBeenCalledWith(403);
    expect(res.json).toHaveBeenCalledWith({ error: 'Forbidden' });
    expect(next).not.toHaveBeenCalled();
  });

  it('allows authenticated requests even from automation user agents', () => {
    const req = {
      headers: {
        authorization: 'Bearer test-token',
        'user-agent': 'Mozilla/5.0 HeadlessChrome/123.0.0.0',
      },
    } as Request;
    const res = createResponse();
    const next = vi.fn();

    blockBots(req, res, next);

    expect(next).toHaveBeenCalledOnce();
    expect(res.status).not.toHaveBeenCalled();
  });

  it('allows public top-board forecast endpoints for headless audits', () => {
    const req = {
      method: 'GET',
      path: '/top-picks',
      headers: {
        'user-agent': 'Mozilla/5.0 HeadlessChrome/123.0.0.0',
      },
    } as Request;
    const res = createResponse();
    const next = vi.fn();

    blockBots(req, res, next);

    expect(next).toHaveBeenCalledOnce();
    expect(res.status).not.toHaveBeenCalled();
  });
});
