import type { Task } from '../types';

export const FILTER_ALL = 'all' as const;
export const CORE_STATUS_FILTERS = ['IN_PROGRESS', 'REVIEW', 'DONE'] as const;

export type CoreStatusFilter = (typeof CORE_STATUS_FILTERS)[number];

export const DEFAULT_STATUS_FILTERS: string[] = [
  FILTER_ALL,
  ...CORE_STATUS_FILTERS,
];

export function isCoreStatusFilter(key: string): key is CoreStatusFilter {
  return (CORE_STATUS_FILTERS as readonly string[]).includes(key);
}

/** UI: 전체·진행·보류·완료 버튼 활성 표시 */
export function isStatusChipActive(
  key: string,
  filters: string[],
  issueMode: boolean,
): boolean {
  if (issueMode) return false;
  if (key === FILTER_ALL) return filters.includes(FILTER_ALL);
  if (isCoreStatusFilter(key)) {
    return filters.includes(FILTER_ALL) || filters.includes(key);
  }
  return false;
}

export function toggleAllFilter(current: string[]): string[] {
  if (current.includes(FILTER_ALL)) {
    return ['IN_PROGRESS'];
  }
  return [...DEFAULT_STATUS_FILTERS];
}

export function toggleCoreFilter(current: string[], key: CoreStatusFilter): string[] {
  if (current.includes(FILTER_ALL)) {
    return CORE_STATUS_FILTERS.filter((k) => k !== key);
  }

  const withoutAll = current.filter((f) => f !== FILTER_ALL);

  if (withoutAll.includes(key)) {
    const next = withoutAll.filter((k) => k !== key);
    return next.length === 0 ? [...DEFAULT_STATUS_FILTERS] : next;
  }

  const next = [...withoutAll, key];
  if (CORE_STATUS_FILTERS.every((k) => next.includes(k))) {
    return [FILTER_ALL, ...next];
  }
  return next;
}

export function taskMatchesStatusFilters(task: Task, filters: string[]): boolean {
  if (filters.includes(FILTER_ALL)) return true;

  return filters.some((key) => {
    if (key === 'IN_PROGRESS') return task.status === 'IN_PROGRESS';
    if (key === 'REVIEW') {
      return task.status === 'REVIEW' || task.status === 'CANCELLED' || task.status === 'TODO';
    }
    if (key === 'DONE') return task.status === 'DONE';
    return false;
  });
}
