import { proxyActivities, sleep } from '@temporalio/workflow';
import { IntegrationsActivity } from '@gitroom/orchestrator/activities/integrations.activity';

const { getIntegrationsById, refreshToken } =
  proxyActivities<IntegrationsActivity>({
    startToCloseTimeout: '10 minute',
    retry: {
      maximumAttempts: 3,
      backoffCoefficient: 1,
      initialInterval: '2 minutes',
    },
  });

export async function refreshTokenWorkflow({
  organizationId,
  integrationId,
}: {
  integrationId: string;
  organizationId: string;
}) {
  while (true) {
    let integration = await getIntegrationsById(integrationId, organizationId);
    if (
      !integration ||
      integration.deletedAt ||
      integration.inBetweenSteps ||
      integration.refreshNeeded
    ) {
      return false;
    }

    const today = new Date();
    const endDate = new Date(integration.tokenExpiration);
    const remainingMs = Math.max(0, endDate.getTime() - today.getTime());

    // Refresh ahead of expiry: 15 minutes early, or half the remaining lifetime when that is shorter
    // (a TikTok access token lives 2 hours; the half rule only matters for forced short test expiries).
    const LEAD_TIME_MS = 15 * 60 * 1000;
    const leadMs = Math.min(LEAD_TIME_MS, Math.floor(remainingMs / 2));
    const waitTimeMs = Math.max(0, remainingMs - leadMs);

    if (waitTimeMs > 0) {
      await sleep(waitTimeMs);

      // while we were sleeping, the integration might have been deleted
      integration = await getIntegrationsById(integrationId, organizationId);
      if (
        !integration ||
        integration.deletedAt ||
        integration.inBetweenSteps ||
        integration.refreshNeeded
      ) {
        return false;
      }
    }

    // A failed refresh ends the loop (the refresh service has already flagged the channel); never retry in a tight loop.
    const refreshed = await refreshToken(integration);
    if (!refreshed) {
      return false;
    }
  }
}
