// src/tests/integration/public.integration.test.ts
import { describe, it, expect } from 'vitest';
import * as apiClient from '../../services/apiClient';

/**
 * @vitest-environment node
 */

describe('Public API Routes Integration Tests', () => {
  describe('Health Check Endpoints', () => {
    it('GET /api/health/ping should return "pong"', async () => {
      const response = await apiClient.pingBackend();
      expect(response.ok).toBe(true);
      expect(await response.text()).toBe('pong');
    });

    it('GET /api/health/db-schema should return success', async () => {
      const response = await apiClient.checkDbSchema();
      const result = await response.json();
      expect(result.success).toBe(true);
      expect(result.message).toBe('All required database tables exist.');
    });

    it('GET /api/health/storage should return success', async () => {
      // This assumes the STORAGE_PATH is correctly set up for the test environment
      const response = await apiClient.checkStorage();
      const result = await response.json();
      expect(result.success).toBe(true);
      expect(result.message).toContain('is accessible and writable');
    });

    it('GET /api/health/db-pool should return success', async () => {
      const response = await apiClient.checkDbPoolHealth();
      // The pingBackend function returns a boolean directly, so no .json() call is needed.
      // However, checkDbPoolHealth returns a Response, so we need to parse it.
      const result = await response.json();
      expect(result.success).toBe(true);
      expect(result.message).toContain('Pool Status:');
    });
  });

  describe('Public Data Endpoints', () => {
    it('GET /api/flyers should return a list of flyers', async () => {
      const response = await apiClient.fetchFlyers();
      const flyers = await response.json();
      expect(flyers).toBeInstanceOf(Array);
      // The seed script creates at least one flyer
      expect(flyers.length).toBeGreaterThan(0);
      expect(flyers[0]).toHaveProperty('flyer_id');
      expect(flyers[0]).toHaveProperty('store');
    });

    it('GET /api/master-items should return a list of master items', async () => {
      const response = await apiClient.fetchMasterItems();
      const masterItems = await response.json();
      expect(masterItems).toBeInstanceOf(Array);
      // The seed script creates master items
      expect(masterItems.length).toBeGreaterThan(0);
      expect(masterItems[0]).toHaveProperty('master_grocery_item_id');
      expect(masterItems[0]).toHaveProperty('category_name');
    });
  });
});