import { describe, it, expect, beforeEach, vi } from 'vitest';
import { get } from 'svelte/store';
import {
  taskDrawerStore,
  openDrawerForTask,
  openDrawerForTaskIfPreferred,
  closeDrawer,
  updateResourceTask,
  setTaskDrawerAutoOpenPreference
} from '../taskDrawer.js';

describe('taskDrawerStore', () => {
  beforeEach(() => {
    setTaskDrawerAutoOpenPreference(true);
    taskDrawerStore.set({
      isOpen: false,
      activeTaskId: null,
      resourceTaskMap: {}
    });
  });

  it('should open drawer for a specific task', () => {
    openDrawerForTask('task-123');
    const state = get(taskDrawerStore);
    expect(state.isOpen).toBe(true);
    expect(state.activeTaskId).toBe('task-123');
  });

  it('should close drawer and clear active task', () => {
    openDrawerForTask('task-123');
    closeDrawer();
    const state = get(taskDrawerStore);
    expect(state.isOpen).toBe(false);
    expect(state.activeTaskId).toBe(null);
  });

  it('should open drawer via preference-aware helper when auto-open is enabled', () => {
    setTaskDrawerAutoOpenPreference(true);
    const opened = openDrawerForTaskIfPreferred('task-123');
    const state = get(taskDrawerStore);

    expect(opened).toBe(true);
    expect(state.isOpen).toBe(true);
    expect(state.activeTaskId).toBe('task-123');
  });

  it('should skip opening drawer via preference-aware helper when auto-open is disabled', () => {
    setTaskDrawerAutoOpenPreference(false);
    const opened = openDrawerForTaskIfPreferred('task-123');
    const state = get(taskDrawerStore);

    expect(opened).toBe(false);
    expect(state.isOpen).toBe(false);
    expect(state.activeTaskId).toBe(null);
  });

  it('should update resource task mapping for running task', () => {
    updateResourceTask('dash-1', 'task-1', 'RUNNING');
    const state = get(taskDrawerStore);
    expect(state.resourceTaskMap['dash-1']).toEqual({ taskId: 'task-1', status: 'RUNNING' });
  });

  it('should remove mapping when task completes (SUCCESS)', () => {
    updateResourceTask('dash-1', 'task-1', 'RUNNING');
    updateResourceTask('dash-1', 'task-1', 'SUCCESS');
    const state = get(taskDrawerStore);
    expect(state.resourceTaskMap['dash-1']).toBeUndefined();
  });

  it('should remove mapping when task fails (ERROR)', () => {
    updateResourceTask('dash-1', 'task-1', 'RUNNING');
    updateResourceTask('dash-1', 'task-1', 'ERROR');
    const state = get(taskDrawerStore);
    expect(state.resourceTaskMap['dash-1']).toBeUndefined();
  });
});
