import { CliTerseError } from '@alwaysai/alwayscli';
import { CliAuthenticationClient, CliRpcClient } from '../../infrastructure';

export async function validateIsUserProject(props: { project: string }) {
  const { project } = props;
  const projectIds = await getUserProjects();

  // if user doesn't have access to project, throw error
  if (!projectIds.includes(project)) {
    throw new CliTerseError(
      'The provided project is not in your list of projects!'
    );
  }
}

export async function getUserProjects() {
  const authInfo = await CliAuthenticationClient().getInfo();

  const projects = await CliRpcClient().listProjectsUserIsCollaborator({
    user_name: authInfo.username
  });
  const projectIds: string[] = [];
  projects.forEach((project, _) => {
    if (project.uuid !== null) {
      projectIds.push(project.uuid);
    }
  });
  return projectIds;
}
