import { baseApiRequest } from "../apiRequests/baseApiRequest";
import { ManagerMemberships, Role, RoleMembership } from "./projectManager";


const API_BASE_URL = "https://ikoncloud-dev.keross.com/ikon-api";

export const getAllRoles = async (): Promise<Role[]> => {
  return await baseApiRequest(
    `${API_BASE_URL}/role`,
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
    },
    {
      isAccessTokenRequird: true,
      
    }
  );
};

export const getRoleMemberships = async (roleId: string): Promise<RoleMembership[]> => {
  return await baseApiRequest(
    `${API_BASE_URL}/role/${roleId}/membership`, 
    {
      method: "GET",
      headers: { "Content-Type": "application/json" },
      credentials: "include",
    },
    {
      isAccessTokenRequird: true,
    }
  );
};

export const getRoleIdByName = (
  roles: Role[],
  roleName: string
): string | undefined => {
  if (!roles || !Array.isArray(roles)) {
    console.error("getRoleIdByName received invalid roles data:", roles);
    return undefined;
  }
  const foundRole = roles.find((role) => role.roleName === roleName);

  return foundRole?.roleId;
};

export const getManagerMemberships = async (): Promise<ManagerMemberships> => {
  try {
    const response = await getAllRoles();
    const allRoles = Array.isArray(response) ? response : (response?.content || []);

    const projectManagerId = getRoleIdByName(allRoles, "Project manager");
    const accountManagerId = getRoleIdByName(allRoles, "Account Manager");

    if (!projectManagerId) {
      console.warn("Could not find roleId for 'Project Manager'");
    }
    if (!accountManagerId) {
      console.warn("Could not find roleId for 'Account Manager'");
    }

    const pmPromise = projectManagerId
      ? getRoleMemberships(projectManagerId)
      : Promise.resolve([]);

    const amPromise = accountManagerId
      ? getRoleMemberships(accountManagerId)
      : Promise.resolve([]);

    const [projectManagerMembers, accountManagerMembers] = await Promise.all([
      pmPromise,
      amPromise,
    ]);

    return {
      projectManagerMembers,
      accountManagerMembers,
    };
  } catch (error) {
    console.error("Error in getManagerMemberships:", error);
    return {
      projectManagerMembers: [],
      accountManagerMembers: [],
    };
  }
};