import apiClient from './index';
import type { Grid, UserAccount } from './types';

export interface GridData extends Grid {}

export type GridWorker = UserAccount;

export interface GridWorkersQuery {
  unassigned?: boolean;
}

/**
 * DTO for updating a grid's core properties.
 * This should align with GridUpdateRequest in the backend.
 */
export interface GridUpdateRequest {
  isObstacle?: boolean;
  description?: string;
}

/**
 * 更新网格信息
 * @param gridId - 要更新的网格ID
 * @param data - 包含更新数据的对象
 * @returns 更新后的网格对象
 */
export function updateGrid(gridId: number, data: GridUpdateRequest): Promise<Grid>;
export function updateGrid(grid: GridData & GridUpdateRequest): Promise<Grid>;
export function updateGrid(
  gridOrId: number | (GridData & GridUpdateRequest),
  data?: GridUpdateRequest
): Promise<Grid> {
  if (typeof gridOrId === 'number') {
    return apiClient.patch(`/grids/${gridOrId}`, data ?? {});
  }
  const payload: GridUpdateRequest = {
    isObstacle: gridOrId.isObstacle,
    description: gridOrId.description,
  };
  return apiClient.patch(`/grids/${gridOrId.id}`, payload);
}

/**
 * 获取所有网格
 */
export const getGrids = (): Promise<GridData[]> => {
  return apiClient.get('/grids');
};

/**
 * 获取网格员列表（可选：仅未分配）
 */
export const getGridWorkers = async (params?: GridWorkersQuery): Promise<GridWorker[]> => {
  const response = await apiClient.get('/personnel/users', {
    params: { role: 'GRID_WORKER' },
  });
  let workers: GridWorker[] = Array.isArray(response) ? response : (response as any).content || [];

  if (params?.unassigned) {
    workers = workers.filter(worker =>
      worker.gridX === null ||
      worker.gridY === null ||
      worker.gridX === undefined ||
      worker.gridY === undefined ||
      worker.gridX === -1 ||
      worker.gridY === -1
    );
  }
  return workers;
};

/**
 * 通过坐标将网格员分配到网格
 * @param gridX - 网格X坐标
 * @param gridY - 网格Y坐标
 * @param userId - 要分配的用户ID
 * @returns 成功则返回void
 */
export const assignWorkerByCoordinates = (gridX: number, gridY: number, userId: number): Promise<void> => {
  return apiClient.post(`/grids/coordinates/${gridX}/${gridY}/assign`, { userId });
};

/**
 * 通过坐标从网格中移除网格员
 * @param gridX - 网格X坐标
 * @param gridY - 网格Y坐标
 * @returns 成功则返回void
 */
export const unassignWorkerByCoordinates = (gridX: number, gridY: number): Promise<void> => {
  return apiClient.post(`/grids/coordinates/${gridX}/${gridY}/unassign`);
};

// Aliases for compatibility with existing usage
export const assignGridWorkerByCoordinates = assignWorkerByCoordinates;
export const removeGridWorkerByCoordinates = unassignWorkerByCoordinates;
