// ============================================================
// Redux Toolkit — Users Slice
// 大厂模式：RTK 管理用户列表的筛选/分页/缓存状态
// 服务端数据获取由 React Query 负责，RTK 负责客户端 UI 状态
// ============================================================

import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import type { KycStatus } from '@/domain/entities';

interface UsersFilters {
  search: string;
  kycStatus: KycStatus | '';
  isActive: boolean | null;
}

interface UsersSliceState {
  filters: UsersFilters;
  page: number;
  pageSize: number;
  selectedIds: string[];
}

const initialState: UsersSliceState = {
  filters: {
    search: '',
    kycStatus: '',
    isActive: null,
  },
  page: 1,
  pageSize: 20,
  selectedIds: [],
};

export const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    setFilters: (state, action: PayloadAction<Partial<UsersFilters>>) => {
      state.filters = { ...state.filters, ...action.payload };
      state.page = 1; // 改筛选条件时重置到第一页
    },
    setPage: (state, action: PayloadAction<number>) => {
      state.page = action.payload;
    },
    setPageSize: (state, action: PayloadAction<number>) => {
      state.pageSize = action.payload;
      state.page = 1;
    },
    toggleSelectUser: (state, action: PayloadAction<string>) => {
      const idx = state.selectedIds.indexOf(action.payload);
      if (idx >= 0) {
        state.selectedIds.splice(idx, 1);
      } else {
        state.selectedIds.push(action.payload);
      }
    },
    clearSelection: (state) => {
      state.selectedIds = [];
    },
    resetFilters: () => initialState,
  },
});

export const { setFilters, setPage, setPageSize, toggleSelectUser, clearSelection, resetFilters } =
  usersSlice.actions;
