import { withHeaders } from "@/record-management/services/api/withHeaders";
import axiosInstance from "@/shared/services/axiosInstance";
import {
  PositionTypeDto,
  PositionTypesListResponse,
} from "@/user-management/dto/positions/positionType";
import { AxiosResponse } from "axios";

export interface PositionTypesHeaders {
  delegatorPositionId: string;
  currentProjectId: string;
}
export interface PositionRequest {
  positionIds: string[];
}

export interface CreatePositionTypePayload {
  name: {
    am: string;
    en: string;
  };
  key: string;
  unitId: string;
}
export interface Params {
  take?: number;
  skip?: number;
  orderBy?: string;
  order?: string;
}

export interface UpdatePositionTypePayload extends Partial<CreatePositionTypePayload> {}

export const positionTypeService = {
  getAll: (
    params?: Record<string, any>,
  ): Promise<AxiosResponse<PositionTypesListResponse>> =>
    axiosInstance.get(`/position-types`, { headers: withHeaders(), params }),

  getById: (id: string): Promise<AxiosResponse<PositionTypeDto>> =>
    axiosInstance.get(`/position-types/${id}`, { headers: withHeaders() }),

  // Types owned by one unit. IAM has no organization-scoped route — position
  // types carry a unitId only, so scoping to an org means filtering by that
  // org's units client-side.
  getByUnitId: (
    unitId: string,
    params?: Params,
  ): Promise<AxiosResponse<PositionTypesListResponse>> =>
    axiosInstance.get(`/position-types/list/${unitId}`, {
      headers: withHeaders(),
      params,
    }),

  // WHERE isSystem = true OR unitId = :unitId — "commons" means the built-in
  // types, not the ones with a null unitId.
  getCommonTypesById: (
    unitId: string,
    params: Params,
  ): Promise<AxiosResponse<PositionTypesListResponse>> =>
    axiosInstance.get(`/position-types/list-with-commons/${unitId}`, {
      headers: withHeaders(),
      params,
    }),

  create: (
    payload: CreatePositionTypePayload,
  ): Promise<AxiosResponse<PositionTypeDto>> =>
    axiosInstance.post(`/position-types`, payload, { headers: withHeaders() }),

  update: (
    id: string,
    payload: UpdatePositionTypePayload,
  ): Promise<AxiosResponse<PositionTypeDto>> =>
    axiosInstance.put(`/position-types/${id}`, payload, {
      headers: withHeaders(),
    }),
  updateFromto: (toId: string, fromId: string): Promise<AxiosResponse> =>
    axiosInstance.patch(
      `/position-types/${toId}/migrate-position-from/${fromId}`,
    ),
  updateByPostion: (
    id: string,
    data: PositionRequest,
  ): Promise<AxiosResponse> =>
    axiosInstance.patch(
      `/position-types/${id}/migrate-position-by-position`,
      data,
    ),
  delete: (id: string): Promise<AxiosResponse<void>> =>
    axiosInstance.delete(`/position-types/${id}`, { headers: withHeaders() }),
};
