import { afterEach, describe, expect, it, vi } from 'vitest';

import { fetchAutomationServiceMonitorState } from '@/services/automationControlService';

describe('automationControlService', () => {
  afterEach(() => {
    vi.unstubAllGlobals();
    vi.restoreAllMocks();
  });

  it('keeps local restart controls available when the dev status payload omits canStart', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
      new Response(JSON.stringify({
        status: 'offline',
        message: '自动化服务离线',
      }), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
        },
      }),
    ));

    const state = await fetchAutomationServiceMonitorState();

    expect(state.status).toBe('offline');
    expect(state.source).toBe('vite-dev-server');
    expect(state.canStart).toBe(true);
  });

  it('keeps local restart controls available when the dev status probe fails', async () => {
    vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')));

    const state = await fetchAutomationServiceMonitorState();

    expect(state.status).toBe('offline');
    expect(state.source).toBe('vite-dev-server');
    expect(state.canStart).toBe(true);
    expect(state.message).toContain('network down');
  });
});