import { CliTerseError } from '@alwaysai/alwayscli';
import { RpcProject } from '@alwaysai/cloud-api';
import { PLEASE_REPORT_THIS_ERROR_MESSAGE } from '../../constants';
import { DeviceMode, CliRpcClient, AaiDevice } from '../../infrastructure';
import { logger } from '../../util';
import { getUpgradeUrl } from './check-for-project-id';

async function checkDeviceLimit(deviceMode: DeviceMode, project: RpcProject) {
  const teamLimits = await CliRpcClient().checkTeamLimits({
    team_id: project.team_id
  });

  if (!teamLimits.enforce_limits) {
    return;
  }

  let deviceLimits;
  switch (deviceMode) {
    case 'development': {
      deviceLimits = teamLimits.dev_devices;
      break;
    }
    case 'production': {
      deviceLimits = teamLimits.prod_devices;
      break;
    }
    default:
      logger.error(`Invalid device mode (${deviceMode}).`);
      throw new CliTerseError(
        `Invalid device mode (${deviceMode}). ${PLEASE_REPORT_THIS_ERROR_MESSAGE}`
      );
  }

  const devicesUsed = deviceLimits.used;
  const devicesLimit = deviceLimits.limit;

  if (devicesLimit !== null && devicesUsed >= devicesLimit) {
    throw new CliTerseError(
      `You've reached your limit of ${deviceMode} devices for this project. Please upgrade to continue: ${await getUpgradeUrl()}`
    );
  }
}

export async function addDeviceToProject(props: {
  device: AaiDevice;
  projectId: string;
}) {
  const { device, projectId } = props;
  const client = CliRpcClient();
  const project = await client.getProjectByUUID({ uuid: projectId });
  const projectDevices = await client.getProjectDevices({
    project_id: project.id
  });
  let deviceInProject = false;
  for (const d of projectDevices) {
    if (d.id === device.id) {
      deviceInProject = true;
      break;
    }
  }
  if (deviceInProject === true) {
    return;
  }

  await checkDeviceLimit(device.mode as DeviceMode, project);
  await client.addProjectDevice({
    device_id: device.id,
    project_id: project.id
  });
}
