import axiosInstance from "@/shared/services/axiosInstance";
import { AxiosResponse } from "axios";
import { withHeaders } from "./withHeaders";

export interface OrgHeaders {
  tenantKey: string;
  unitId?: string;
}

export interface OrganizationPayload {
  name: {
    am: string;
    en: string;
  };
  key: string;
  organizationTypeId: string;
  parentId?: string;
}

export interface OrgQueryParams {
  orderBy?: string;
  take?: number;
  skip?: number;
}

export const getOrganizations = async (
  params?: OrgQueryParams
): Promise<AxiosResponse> => {
  return axiosInstance.get("/organizations", {
    ...withHeaders(),
    params,
  });
};

export const getOrganizationById = async (
  id: string | number
): Promise<AxiosResponse> => {
  return axiosInstance.get(`/organizations/${id}`, { headers: withHeaders() });
};

export const getChildren = async (
  id: string | number
): Promise<AxiosResponse> => {
  return axiosInstance.get(`/organizations/${id}/children`, {
    headers: withHeaders(),
  });
};

export const getEmployeesUnderOrg = async (
  id: string | number,
  params?: OrgQueryParams
): Promise<AxiosResponse> => {
  return axiosInstance.get(`/organizations/current/${id}/employees`, {
    headers: withHeaders(),
    params: {
      take: 1000, // Get a large number of employees by default
      skip: 0,
      ...params,
    },
  });
};

export const createOrganization = async (
  data: OrganizationPayload
): Promise<AxiosResponse> => {
  return axiosInstance.post("/organizations", data, { headers: withHeaders() });
};

export const updateOrganization = async (
  id: string | number,
  data: OrganizationPayload
): Promise<AxiosResponse> => {
  return axiosInstance.put(`/organizations/${id}`, data, {
    headers: withHeaders(),
  });
};

export const deleteOrganization = async (
  id: string | number
): Promise<AxiosResponse> => {
  return axiosInstance.delete(`/organizations/${id}`, {
    headers: withHeaders(),
  });
};
