import api from "../axios";

export interface Role {
  id: string;
  title: string;
  moniker: string;
  permissions: string[];
  createdAt: string;
  updatedAt: string;
}

export const role = {
  async fetchMany(accessToken: string) {
    const response = await api.get("/v1/role", {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async fetch(accessToken: string, identifier: string) {
    const response = await api.get(`/v1/role/${identifier}`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async create(
    accessToken: string,
    data: Omit<Role, "id" | "createdAt" | "updatedAt">,
  ) {
    const response = await api.post("/v1/role", data, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async update(
    accessToken: string,
    identifier: string,
    updates: Partial<Omit<Role, "id" | "createdAt" | "updatedAt">>,
  ) {
    const response = await api.patch(`/v1/role/${identifier}`, updates, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async delete(accessToken: string, identifier: string) {
    const response = await api.delete(`/v1/role/${identifier}`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },

  async addPermissions(
    accessToken: string,
    identifier: string,
    permissions: string[],
  ) {
    const response = await api.post(
      `/v1/role/${identifier}/permissions`,
      { permissions },
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      },
    );
    return response.data;
  },

  async removePermissions(
    accessToken: string,
    identifier: string,
    permissions: string[],
  ) {
    const response = await api.delete(`/v1/role/${identifier}/permissions`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
      data: { permissions },
    });
    return response.data;
  },

  async fetchUsers(accessToken: string, identifier: string) {
    const response = await api.get(`/v1/role/${identifier}/users`, {
      headers: {
        Authorization: `Bearer ${accessToken}`,
      },
    });
    return response.data;
  },
};
