import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { useBackend } from './useBackend';
import type { MetaResponse } from '~/types/api/meta';
import type { ContactResponse } from '~/types/api/contact';

// Mock useApi
const mockGet = vi.fn();
const mockPost = vi.fn();

vi.mock('./useApi', () => ({
  useApi: vi.fn(() => ({
    get: mockGet,
    post: mockPost,
  })),
}));

describe('useBackend', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe('getMeta', () => {
    it('should call useApi.get with /meta endpoint', () => {
      const mockResult = {
        data: ref<MetaResponse | null>({ version: '1.0.0', name: 'Test' }),
        error: ref(null),
        loading: ref(false),
        run: vi.fn(),
      };
      mockGet.mockReturnValue(mockResult);

      const { getMeta } = useBackend();
      const result = getMeta();

      expect(mockGet).toHaveBeenCalledWith('/meta');
      expect(result).toBe(mockResult);
    });

    it('should return UseApiResponse with correct structure', () => {
      const mockResult = {
        data: ref<MetaResponse | null>(null),
        error: ref(null),
        loading: ref(false),
        run: vi.fn(),
      };
      mockGet.mockReturnValue(mockResult);

      const { getMeta } = useBackend();
      const result = getMeta();

      expect(result).toHaveProperty('data');
      expect(result).toHaveProperty('error');
      expect(result).toHaveProperty('loading');
      expect(result).toHaveProperty('run');
    });
  });

  describe('postContact', () => {
    it('should call useApi.post with /contact endpoint and immediate=false', () => {
      const mockResult = {
        data: ref<ContactResponse | null>(null),
        error: ref(null),
        loading: ref(false),
        run: vi.fn(),
      };
      mockPost.mockReturnValue(mockResult);

      const { postContact } = useBackend();
      const result = postContact();

      expect(mockPost).toHaveBeenCalledWith('/contact', undefined, false);
      expect(result).toBe(mockResult);
    });

    it('should return UseApiResponse with correct structure', () => {
      const mockResult = {
        data: ref<ContactResponse | null>(null),
        error: ref(null),
        loading: ref(false),
        run: vi.fn(),
      };
      mockPost.mockReturnValue(mockResult);

      const { postContact } = useBackend();
      const result = postContact();

      expect(result).toHaveProperty('data');
      expect(result).toHaveProperty('error');
      expect(result).toHaveProperty('loading');
      expect(result).toHaveProperty('run');
    });
  });
});
