import { describe, it, expect, beforeEach, vi } from 'vitest';
import { setActivePinia, createPinia } from 'pinia';
import axios from 'axios';
import { useProjectsStore } from '../../resources/js/stores/projectsStore';

vi.mock('axios');

describe('projectsStore.bulkUpdate', () => {
    beforeEach(() => {
        setActivePinia(createPinia());
        vi.mocked(axios.post).mockResolvedValue({ data: { updated: 2, skipped: [], warnings: [] } });
        vi.mocked(axios.get).mockResolvedValue({ data: { data: [], meta: { total: 0 } } });
    });

    it('sends ids array when selectAllByFilter=false', async () => {
        const store = useProjectsStore();
        store.selectedIds.add(3);
        store.selectedIds.add(7);

        await store.bulkUpdate({ action: 'pause' });

        expect(axios.post).toHaveBeenCalledWith('/api/projects/bulk', {
            action: 'pause',
            ids: [3, 7],
        });
    });

    it('sends scope.filter when selectAllByFilter=true', async () => {
        const store = useProjectsStore();
        store.selectAllByFilter = true;
        store.filters.signal_type = 'sms';
        store.filters.status = 'active';
        store.filters.search = 'окна';

        await store.bulkUpdate({ action: 'update_regions', add_regions: [3, 5], remove_regions: [1] });

        expect(axios.post).toHaveBeenCalledWith('/api/projects/bulk', {
            action: 'update_regions',
            add_regions: [3, 5],
            remove_regions: [1],
            scope: { filter: { signal_type: 'sms', status: 'active', search: 'окна' } },
        });
    });

    it('toggleSelect drops out of selectAllByFilter mode', () => {
        const store = useProjectsStore();
        store.selectAllByFilter = true;
        store.selectedIds.add(1);
        store.selectedIds.add(2);

        store.toggleSelect(1);

        expect(store.selectAllByFilter).toBe(false);
        expect(store.selectedIds.has(1)).toBe(false);
        expect(store.selectedIds.has(2)).toBe(true);
    });

    it('clears selection after successful bulkUpdate', async () => {
        const store = useProjectsStore();
        store.selectedIds.add(1);
        store.selectAllByFilter = true;

        await store.bulkUpdate({ action: 'pause' });

        expect(store.selectedIds.size).toBe(0);
        expect(store.selectAllByFilter).toBe(false);
    });
});
