import { describe, it, expect } from 'vitest';
import type { LocalTask } from '../api';
import { filterAndSortTasks, groupTasksByStatus, statusCounts, totalTaskCount } from './taskFilter';

function task(p: Partial<LocalTask> & { id: number }): LocalTask {
  return {
    title: `task ${p.id}`,
    body: '',
    pieceName: 'auto',
    ownerName: null,
    updatedAt: '2026-01-01T00:00:00Z',
    latestJob: { status: 'queued' },
    ...p,
  } as LocalTask;
}

describe('taskFilter', () => {
  const tasks = [
    task({ id: 1, title: 'Weekly report', latestJob: { status: 'running' } as LocalTask['latestJob'], updatedAt: '2026-01-03T00:00:00Z' }),
    task({ id: 2, title: 'Invoice parse', body: 'parse the pdf', latestJob: { status: 'succeeded' } as LocalTask['latestJob'], updatedAt: '2026-01-02T00:00:00Z' }),
    task({ id: 3, title: 'Daily digest', pieceName: 'research', latestJob: { status: 'failed' } as LocalTask['latestJob'], updatedAt: '2026-01-01T00:00:00Z' }),
  ];

  it('counts and totals by status', () => {
    const cols = groupTasksByStatus(tasks);
    const counts = statusCounts(cols);
    expect(counts.running).toBe(1);
    expect(counts.succeeded).toBe(1);
    expect(counts.failed).toBe(1);
    expect(totalTaskCount(cols)).toBe(3);
  });

  it('filters by free-text search across title/body/piece/ownerName', () => {
    expect(filterAndSortTasks(tasks, 'all', 'invoice', 'updated').map(t => t.id)).toEqual([2]);
    expect(filterAndSortTasks(tasks, 'all', 'pdf', 'updated').map(t => t.id)).toEqual([2]); // body
    expect(filterAndSortTasks(tasks, 'all', 'research', 'updated').map(t => t.id)).toEqual([3]); // pieceName
    expect(filterAndSortTasks(tasks, 'all', 'zzz', 'updated')).toHaveLength(0);
    // ownerName field
    const withOwner = [...tasks, task({ id: 4, ownerName: 'Tanaka' })];
    expect(filterAndSortTasks(withOwner, 'all', 'tanaka', 'updated').map(t => t.id)).toEqual([4]);
  });

  it('filters by status column', () => {
    expect(filterAndSortTasks(tasks, 'running', '', 'updated').map(t => t.id)).toEqual([1]);
    expect(filterAndSortTasks(tasks, 'failed', '', 'updated').map(t => t.id)).toEqual([3]);
  });

  it('sorts by updated (desc), title, and status', () => {
    expect(filterAndSortTasks(tasks, 'all', '', 'updated').map(t => t.id)).toEqual([1, 2, 3]);
    expect(filterAndSortTasks(tasks, 'all', '', 'title').map(t => t.title)).toEqual([
      'Daily digest', 'Invoice parse', 'Weekly report',
    ]);
    // status sort: alphabetical by status string → failed(3) < running(1) < succeeded(2)
    expect(filterAndSortTasks(tasks, 'all', '', 'status').map(t => t.id)).toEqual([3, 1, 2]);
  });
});
