import { getAllRoles, getAllUsers, getRoleMemberships, getUserById } from ".";
import { ManagerMemberships, Role, UserInfo } from "./type"; // Import User

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 findUsersInRole = async (roleName: string) => {
  try {
    console.log("Step 1: Fetching all roles...");
    const allRoles = await getAllRoles();

    console.log(`Step 2: Finding ID for role "${roleName}"...`);
    const roleId = getRoleIdByName(allRoles, roleName);

    if (!roleId) {
      console.error(`Error: Role "${roleName}" not found.`);
      return;
    }

    console.log(`Found roleId: ${roleId}`);

    console.log("Step 3: Fetching memberships for this role...");
    const memberships = await getRoleMemberships(roleId);

    if (memberships.length === 0) {
      console.log(`No users found for role "${roleName}".`);
      return;
    }

    console.log(
      `Success! Found ${memberships.length} user(s) in "${roleName}":`
    );

    const userIds = memberships.map((m: { userId: string }) => m.userId);
    console.log(userIds);
    return userIds;
  } catch (error) {
    console.error("An error occurred during the process:", error);
  }
};

export const getManagerMemberships = async (): Promise<ManagerMemberships> => {
  try {
    const response = await getAllRoles();
    const allRoles = Array.isArray(response) ? response : (response?.content || []);
    console.log("rolesss", allRoles);
    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: [],
    };
  }
};

export const createUserMaps = async (): Promise<{
  nameMap: Map<string, string>;
  designationMap: Map<string, string | null>;
}> => {
  const nameMap = new Map<string, string>();
  const designationMap = new Map<string, string | null>();

  try {
    const response = await getAllUsers();
    const userArray = response ?? response;

    if (!userArray || !Array.isArray(userArray) || userArray.length === 0) {
      return { nameMap, designationMap };
    } else {
      for (const user of userArray) {
        if (user?.userId) {
          nameMap.set(user.userId, user.userName);
          designationMap.set(user.userId, user.userDesignation);
        }
      }
    }

    return { nameMap, designationMap };
  } catch (error) {
    console.error("Failed to fetch users and create maps:", error);
    return { nameMap, designationMap };
  }
};

export const getUserNameById = async (
  userId: string
): Promise<string | undefined> => {
  try {
    const user = await getUserById(userId);
    return user?.userName;
  } catch (error) {
    console.error("Failed to get user name by ID:", error);
  }
};

export const getUserInfo = async (userId: string): Promise<UserInfo | null> => {
  const user = await getUserById(userId);

  if (!user) {
    return null;
  }

  return {
    userName: user.userName,
    userLogin: user.userLogin,
    userEmail: user.userEmail,
  };
};
