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

import {
  fetchAutomationServiceMonitorState,
  restartAutomationServiceFromDevServer,
} 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');
  });

  it('keeps restart-sent as a busy restart state from the dev server', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
      new Response(JSON.stringify({
        status: 'restart-sent',
        canStart: true,
        message: '已向自动化服务守护进程发送重启请求',
      }), {
        status: 202,
        headers: {
          'Content-Type': 'application/json',
        },
      }),
    ));

    const state = await restartAutomationServiceFromDevServer();

    expect(state.status).toBe('restart-sent');
    expect(state.canStart).toBe(true);
    expect(state.message).toContain('重启请求');
  });

  it('normalizes unmanaged dev status without reporting it as offline', async () => {
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue(
      new Response(JSON.stringify({
        status: 'unmanaged',
        canStart: false,
        message: '端口已有自动化 API，但不归当前 supervisor 管理',
      }), {
        status: 200,
        headers: {
          'Content-Type': 'application/json',
        },
      }),
    ));

    const state = await fetchAutomationServiceMonitorState();

    expect(state.status).toBe('unmanaged');
    expect(state.canStart).toBe(false);
    expect(state.message).toContain('不归当前 supervisor 管理');
  });

  it('explains restart failures when the Vite control endpoint is unreachable', async () => {
    vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Failed to fetch')));

    await expect(restartAutomationServiceFromDevServer()).rejects.toThrow('Vite 开发服务控制接口不可用');
  });
});
