import { CliTerseError } from '@alwaysai/alwayscli';
import { CliAuthenticationClient, CliRpcClient } from '../../infrastructure';
import { getUpgradeUrl } from './check-for-project-id';

export async function checkPaidPlan() {
  const { username } = await CliAuthenticationClient().getInfo();

  const client = CliRpcClient();
  const teams = await client.listTeamsUserIsOwner({ user_name: username });
  if (teams.length === 0) {
    throw new CliTerseError(
      'You are not a member of a team, please join a team to continue.'
    );
  }
  // FIXME: Handle multiple teams
  const teamLimits = await client.checkTeamLimits({
    team_id: teams[0].id
  });

  const planName = teamLimits['plan_name'];

  if (planName === 'Free' || planName === 'unknown') {
    return false;
  }
  return true;
}

export async function requirePaidPlan() {
  const isPaid = await checkPaidPlan();
  if (!isPaid) {
    throw new CliTerseError(
      `This feature is only available for Basic or Premium users. Please upgrade to continue: ${getUpgradeUrl()}`
    );
  }
}
