import { apiSlice } from ".";
import { generateQueryString } from "@/utils/queryStringUtil";
import URLS from "./constants";


export interface Role {
    id: string;
    name: string;
    description?: string;
    permissions?: { id: string }[];
    parentRole?: { id: string } | string;
    createdBy?: { id: string };
    updatedBy?: { id: string };
    company?: { id: string } | string;
    message?: string;
    success?: boolean;
  }
  
  interface GetRolesListResponse {
    code: number;
    message: string;
    success: boolean;
    data: {
      results: Role[];
      page: number;
      limit: number;
      totalPages: number;
      totalResults: number;
    };
  }
  
  interface GetRoleByIdResponse {
    code: number;
    message: string;
    success: boolean;
    data: Role;
  }

  export const roleApi = apiSlice.injectEndpoints({
    endpoints: (builder) => ({
      getRoles: builder.query<
        GetRolesListResponse,
        {
          page?: number;
          limit?: number;
          search?: string;
          company?: string;
          populate?: string;
          includeTimeStamps?: boolean;
          sortBy?: string;
        }
      >({
        query: (params) => ({
          url: `${URLS.ROLES}?${generateQueryString(params as Record<string, unknown>)}`,
          method: "GET",
        }),
        providesTags: ["Role"],
      }),
  
      getRoleById: builder.query<GetRoleByIdResponse, string>({
        query: (id) => ({
          url: `${URLS.ROLES}/${id}`,
          method: "GET",
        }),
      }),
  
      createRole: builder.mutation<Role, Partial<Role>>({
        query: (body) => ({
          url: `${URLS.ROLES}`,
          method: "POST",
          body,
        }),
        invalidatesTags: ["Role"],
      }),
  
      updateRole: builder.mutation<Role, { id: string } & Partial<Role>>({
        query: ({ id, ...body }) => ({
          url: `${URLS.ROLES}/${id}`,
          method: "PATCH",
          body,
        }),
        invalidatesTags: ["Role"],
      }),
  
      deleteRole: builder.mutation<{ success: boolean }, string>({
        query: (id) => ({
          url: `${URLS.ROLES}/${id}`,
          method: "DELETE",
        }),
        invalidatesTags: ["Role"],
      }),
    }),
  });

  export const {
    useGetRolesQuery,
    useGetRoleByIdQuery,
    useCreateRoleMutation,
    useUpdateRoleMutation,
    useDeleteRoleMutation,
  } = roleApi;