import qs from 'qs';

import api from 'src/config/api';
import {
  type ApprovalGroup,
  type ApprovalGroupTask,
  type ApprovalStateName,
  ServiceItemTypes,
  type TaskChild,
  TasksType,
} from 'src/pages/dashboard/serviceManagement/types';
import { type Pagination } from 'src/types/services';

export const getApprovalGroups = (
  taskId: string,
  params: Record<string, unknown>,
) =>
  api.get<Pagination<ApprovalGroup[]>>(
    `workflows/tasks/${taskId}/approval-groups`,
    {
      params,
    },
  );

export const getApprovalGroup = (taskId: string, approvalGroupId: string) =>
  api.get<Pagination<ApprovalGroupTask[]>>(
    `workflows/tasks/${taskId}/approval-groups/${approvalGroupId}/tasks`,
  );

export const getApprovalGroupsCount = (
  taskId: string,
  statusIn?: ApprovalStateName[],
) =>
  api.get(`workflows/tasks/${taskId}/approval-groups/count`, {
    params: {
      statusIn: statusIn || undefined,
    },
    paramsSerializer: params => qs.stringify(params, { arrayFormat: 'comma' }),
  });

export const getCountForTaskType = (
  role: TasksType = TasksType.AGENT,
  type: ServiceItemTypes = ServiceItemTypes.APPROVAL,
  closed?: boolean,
) =>
  api.get<{ count: number }>(`workflows/tasks/count`, {
    params: {
      role,
      type,
      closed: closed ?? null,
    },
  });

export const getApprovalTasks = (
  taskId: string,
  params: Record<string, unknown>,
) =>
  api.get<Pagination<TaskChild[]>>(`workflows/tasks/${taskId}/children`, {
    params,
  });

export const getTasksCount = (taskId: string, closed?: boolean) =>
  api.get<{ count: number }>(`workflows/tasks/${taskId}/children/count`, {
    params: {
      role: TasksType.AGENT,
      type: ServiceItemTypes.SUBTASK,
      closed: closed ?? null,
    },
  });
