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

import type { CustomerListItemDto, CustomerListStatsDto } from '#/api/customer';
import type { StoreListItemDto } from '#/api/store';

import { getCustomerListApi, getCustomerListStatsApi } from '#/api/customer';
import { getStoreListApi } from '#/api/store';

import { DEFAULT_STATS } from './constants';
import { buildFilterPayload, buildQueryPayload } from './helpers';

interface DataActionOptions {
  filters: CustomerFilterState;
  isListLoading: { value: boolean };
  isStatsLoading: { value: boolean };
  isStoreLoading: { value: boolean };
  pagination: CustomerPaginationState;
  rows: { value: CustomerListItemDto[] };
  selectedStoreId: { value: string };
  stats: CustomerListStatsDto;
  stores: { value: StoreListItemDto[] };
}

/**
 * 文件职责：客户列表页数据加载动作。
 */
export function createDataActions(options: DataActionOptions) {
  function resetStats() {
    options.stats.totalCustomers = DEFAULT_STATS.totalCustomers;
    options.stats.monthlyNewCustomers = DEFAULT_STATS.monthlyNewCustomers;
    options.stats.monthlyGrowthRatePercent =
      DEFAULT_STATS.monthlyGrowthRatePercent;
    options.stats.activeCustomers = DEFAULT_STATS.activeCustomers;
    options.stats.averageAmountLast30Days =
      DEFAULT_STATS.averageAmountLast30Days;
  }

  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({ page: 1, pageSize: 200 });
      options.stores.value = result.items;

      if (result.items.length === 0) {
        options.selectedStoreId.value = '';
        options.rows.value = [];
        options.pagination.total = 0;
        resetStats();
        return;
      }

      const matched = result.items.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!matched) {
        options.selectedStoreId.value = result.items[0]?.id ?? '';
      }
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadPageData() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      options.pagination.total = 0;
      resetStats();
      return;
    }

    const queryPayload = buildQueryPayload(
      options.selectedStoreId.value,
      options.filters,
      options.pagination.page,
      options.pagination.pageSize,
    );
    const filterPayload = buildFilterPayload(
      options.selectedStoreId.value,
      options.filters,
    );

    options.isListLoading.value = true;
    options.isStatsLoading.value = true;
    try {
      const [listResult, statsResult] = await Promise.all([
        getCustomerListApi(queryPayload),
        getCustomerListStatsApi(filterPayload),
      ]);

      options.rows.value = listResult.items;
      options.pagination.total = listResult.total;
      options.pagination.page = listResult.page;
      options.pagination.pageSize = listResult.pageSize;

      options.stats.totalCustomers = statsResult.totalCustomers;
      options.stats.monthlyNewCustomers = statsResult.monthlyNewCustomers;
      options.stats.monthlyGrowthRatePercent =
        statsResult.monthlyGrowthRatePercent;
      options.stats.activeCustomers = statsResult.activeCustomers;
      options.stats.averageAmountLast30Days =
        statsResult.averageAmountLast30Days;
    } finally {
      options.isListLoading.value = false;
      options.isStatsLoading.value = false;
    }
  }

  return {
    loadPageData,
    loadStores,
    resetStats,
  };
}
