/**
 * Tests for get_mep_declarations MCP tool
 */

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { handleGetMEPDeclarations, getMEPDeclarationsToolMetadata } from './getMEPDeclarations.js';
import * as epClientModule from '../clients/europeanParliamentClient.js';

// Mock the EP client
vi.mock('../clients/europeanParliamentClient.js', () => ({
  epClient: {
    getMEPDeclarations: vi.fn(),
    getMEPDeclarationById: vi.fn()
  }
}));

describe('get_mep_declarations Tool', () => {
  beforeEach(() => {
    vi.clearAllMocks();

    // Setup default mock implementation
    vi.mocked(epClientModule.epClient.getMEPDeclarations).mockResolvedValue({
      data: [
        {
          id: 'dec/2024/001',
          title: 'Declaration of financial interests',
          mepId: 'person/124936',
          mepName: 'Jane Andersson',
          type: 'FINANCIAL_INTERESTS',
          dateFiled: '2024-01-15',
          status: 'PUBLISHED'
        }
      ],
      total: 1,
      limit: 50,
      offset: 0,
      hasMore: false
    });
  });

  describe('Input Validation', () => {
    it('should accept empty arguments and apply defaults', async () => {
      const result = await handleGetMEPDeclarations({});
      expect(result).toHaveProperty('content');
      expect(result.content[0]?.type).toBe('text');
    });

    it('should accept valid year filter', async () => {
      const result = await handleGetMEPDeclarations({ year: 2024 });
      expect(result).toHaveProperty('content');
    });

    it('should accept valid limit and offset', async () => {
      const result = await handleGetMEPDeclarations({ limit: 25, offset: 10 });
      expect(result).toHaveProperty('content');
    });

    it('should reject year below minimum', async () => {
      await expect(handleGetMEPDeclarations({ year: 1989 })).rejects.toThrow();
    });

    it('should reject year above maximum', async () => {
      await expect(handleGetMEPDeclarations({ year: 2041 })).rejects.toThrow();
    });

    it('should reject limit below minimum', async () => {
      await expect(handleGetMEPDeclarations({ limit: 0 })).rejects.toThrow();
    });

    it('should reject limit above maximum', async () => {
      await expect(handleGetMEPDeclarations({ limit: 101 })).rejects.toThrow();
    });

    it('should reject negative offset', async () => {
      await expect(handleGetMEPDeclarations({ offset: -1 })).rejects.toThrow();
    });
  });

  describe('Response Format', () => {
    it('should return MCP-compliant response structure', async () => {
      const result = await handleGetMEPDeclarations({});

      expect(result).toHaveProperty('content');
      expect(Array.isArray(result.content)).toBe(true);
      expect(result.content).toHaveLength(1);
      expect(result.content[0]).toHaveProperty('type', 'text');
      expect(result.content[0]).toHaveProperty('text');
    });

    it('should return valid JSON in text field', async () => {
      const result = await handleGetMEPDeclarations({});
      const text = result.content[0]?.text;

      expect(() => {
        const parsed: unknown = JSON.parse(text ?? '');
        return parsed;
      }).not.toThrow();
    });

    it('should return paginated response with declaration data', async () => {
      const result = await handleGetMEPDeclarations({});
      const text = result.content[0]?.text ?? '{}';
      const data: unknown = JSON.parse(text);

      expect(data).toHaveProperty('data');
      expect(data).toHaveProperty('total');
      expect(data).toHaveProperty('limit');
      expect(data).toHaveProperty('offset');
      expect(data).toHaveProperty('hasMore');
    });
  });

  describe('Error Handling', () => {
    it('should propagate API client errors', async () => {
      vi.mocked(epClientModule.epClient.getMEPDeclarations)
        .mockRejectedValueOnce(new Error('Unauthorized'));

      await expect(handleGetMEPDeclarations({})).rejects.toThrow('Failed to retrieve MEP declarations');
    });

    it('should propagate schema validation errors for invalid input', async () => {
      await expect(handleGetMEPDeclarations({ year: 'invalid' })).rejects.toThrow();
    });
  });

  describe('Client Invocation', () => {
    it('should pass year filter to client when provided', async () => {
      await handleGetMEPDeclarations({ year: 2024, limit: 10 });

      expect(epClientModule.epClient.getMEPDeclarations).toHaveBeenCalledWith(
        expect.objectContaining({
          year: 2024,
          limit: 10,
          offset: 0
        })
      );
    });

    it('should not pass undefined year to client', async () => {
      await handleGetMEPDeclarations({ limit: 20 });

      const callArgs = vi.mocked(epClientModule.epClient.getMEPDeclarations).mock.calls[0]?.[0];
      expect(callArgs).not.toHaveProperty('year');
    });
  });

  describe('Metadata', () => {
    it('should export tool metadata with correct name', () => {
      expect(getMEPDeclarationsToolMetadata).toHaveProperty('name', 'get_mep_declarations');
    });

    it('should export tool metadata with description', () => {
      expect(getMEPDeclarationsToolMetadata).toHaveProperty('description');
      expect(getMEPDeclarationsToolMetadata.description.length).toBeGreaterThan(0);
    });

    it('should export tool metadata with inputSchema', () => {
      expect(getMEPDeclarationsToolMetadata).toHaveProperty('inputSchema');
      expect(getMEPDeclarationsToolMetadata.inputSchema).toHaveProperty('type', 'object');
      expect(getMEPDeclarationsToolMetadata.inputSchema).toHaveProperty('properties');
    });

    it('should define year, limit, offset in schema', () => {
      const props = getMEPDeclarationsToolMetadata.inputSchema.properties;
      expect(props).toHaveProperty('year');
      expect(props).toHaveProperty('limit');
      expect(props).toHaveProperty('offset');
    });

    it('should mention GDPR in description', () => {
      expect(getMEPDeclarationsToolMetadata.description).toContain('GDPR');
    });
  });

  describe('docId lookup branch', () => {
    it('should call getMEPDeclarationById when docId is provided', async () => {
      const mockDeclaration = {
        id: 'dec/2024/001',
        title: 'Declaration of financial interests',
        date: '2024-01-15',
        mepId: 'MEP-124810',
        type: 'financial',
        content: 'Declaration content'
      };
      vi.mocked(epClientModule.epClient.getMEPDeclarationById).mockResolvedValue(mockDeclaration);

      const result = await handleGetMEPDeclarations({ docId: 'dec/2024/001' });
      expect(result.content[0].type).toBe('text');
      const parsed = JSON.parse(result.content[0].text) as { id: string };
      expect(parsed.id).toBe('dec/2024/001');
    });
  });
});
