import type { CustomerFilterState, CustomerPaginationState } from '../../types';

import { createDefaultFilters } from './constants';

interface FilterActionOptions {
  filters: CustomerFilterState;
  loadPageData: () => Promise<void>;
  pagination: CustomerPaginationState;
}

/**
 * 文件职责：客户列表筛选与分页动作。
 */
export function createFilterActions(options: FilterActionOptions) {
  function setTag(value: string) {
    options.filters.tag = (value || 'all') as CustomerFilterState['tag'];
  }

  function setOrderCountRange(value: string) {
    options.filters.orderCountRange = (value ||
      'all') as CustomerFilterState['orderCountRange'];
  }

  function setRegisterPeriod(value: string) {
    options.filters.registerPeriod = (value ||
      'all') as CustomerFilterState['registerPeriod'];
  }

  function setKeyword(value: string) {
    options.filters.keyword = value;
  }

  async function handleSearch() {
    options.pagination.page = 1;
    await options.loadPageData();
  }

  async function handleReset() {
    const defaults = createDefaultFilters();
    options.filters.keyword = defaults.keyword;
    options.filters.tag = defaults.tag;
    options.filters.orderCountRange = defaults.orderCountRange;
    options.filters.registerPeriod = defaults.registerPeriod;
    options.pagination.page = 1;
    await options.loadPageData();
  }

  async function handlePageChange(page: number, pageSize: number) {
    options.pagination.page = page;
    options.pagination.pageSize = pageSize;
    await options.loadPageData();
  }

  return {
    handlePageChange,
    handleReset,
    handleSearch,
    setKeyword,
    setOrderCountRange,
    setRegisterPeriod,
    setTag,
  };
}
