import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
  acknowledgePolicyDocument,
  listMyPolicyAcknowledgments,
} from '@/shared/api/policyAcknowledgments';
import { apiRequest } from '@/shared/api/httpClient';
import type { ApiListResponse } from '@/shared/types/api';
import type { PolicyAcknowledgmentDto } from '@/shared/types/policyDocuments';

vi.mock('@/shared/api/httpClient', () => ({
  apiRequest: vi.fn(),
}));

const apiRequestMock = vi.mocked(apiRequest);

describe('policyAcknowledgments API', () => {
  beforeEach(() => {
    apiRequestMock.mockReset();
  });

  describe('listMyPolicyAcknowledgments', () => {
    it('fetches all acknowledgments when no document ID is provided', async () => {
      const response: ApiListResponse<PolicyAcknowledgmentDto> = {
        rows: [
          {
            id: 'ack-1',
            policyDocumentId: 'doc-1',
            version: 1,
            userId: 'user-1',
            acknowledgedAt: '2024-01-01T00:00:00Z',
            organizationId: 'org-1',
            campusId: 'campus-1',
            createdAt: '2024-01-01T00:00:00Z',
            updatedAt: '2024-01-01T00:00:00Z',
          },
        ],
        count: 1,
      };
      apiRequestMock.mockResolvedValueOnce(response);

      await expect(listMyPolicyAcknowledgments()).resolves.toEqual(response);

      expect(apiRequestMock).toHaveBeenCalledWith('/policy_acknowledgments');
    });

    it('fetches acknowledgments for a specific document when ID is provided', async () => {
      const response: ApiListResponse<PolicyAcknowledgmentDto> = {
        rows: [],
        count: 0,
      };
      apiRequestMock.mockResolvedValueOnce(response);

      await expect(listMyPolicyAcknowledgments('doc-123')).resolves.toEqual(
        response,
      );

      expect(apiRequestMock).toHaveBeenCalledWith(
        '/policy_acknowledgments?policyDocumentId=doc-123',
      );
    });
  });

  describe('acknowledgePolicyDocument', () => {
    it('acknowledges a policy document', async () => {
      const acknowledgment: PolicyAcknowledgmentDto = {
        id: 'ack-new',
        policyDocumentId: 'doc-1',
        version: 1,
        userId: 'user-1',
        acknowledgedAt: '2024-01-15T10:00:00Z',
        organizationId: 'org-1',
        campusId: 'campus-1',
        createdAt: '2024-01-15T10:00:00Z',
        updatedAt: '2024-01-15T10:00:00Z',
      };
      apiRequestMock.mockResolvedValueOnce(acknowledgment);

      await expect(
        acknowledgePolicyDocument({ policyDocumentId: 'doc-1' }),
      ).resolves.toEqual(acknowledgment);

      expect(apiRequestMock).toHaveBeenCalledWith('/policy_acknowledgments', {
        method: 'POST',
        body: { data: { policyDocumentId: 'doc-1' } },
      });
    });
  });
});
