import { CodeartifactClient, GetAuthorizationTokenCommand } from "@aws-sdk/client-codeartifact";
import type { Logger } from "pino";

const REFRESH_INTERVAL_MS = 4 * 60 * 60 * 1000; // 4 hours
const TOKEN_DURATION_SECONDS = 43200; // 12 hours

export interface CodeArtifactConfig {
  domain: string;
  domainOwner: string;
  region: string;
}

async function fetchToken(client: CodeartifactClient, cfg: CodeArtifactConfig): Promise<string> {
  const command = new GetAuthorizationTokenCommand({
    domain: cfg.domain,
    domainOwner: cfg.domainOwner,
    durationSeconds: TOKEN_DURATION_SECONDS,
  });

  const response = await client.send(command);

  if (!response.authorizationToken) {
    throw new Error("CodeArtifact returned empty authorization token");
  }

  return response.authorizationToken;
}

/**
 * Fetches a CodeArtifact token immediately and schedules automatic refresh every 4 hours.
 * Returns a cleanup function to clear the refresh interval.
 */
export async function configureCodeArtifactAuth(
  cfg: CodeArtifactConfig,
  logger: Logger,
): Promise<() => void> {
  const client = new CodeartifactClient({ region: cfg.region });

  process.env.CODEARTIFACT_AUTH_TOKEN = await fetchToken(client, cfg);
  logger.info("codeartifact_auth_configured");

  const interval = setInterval(async () => {
    try {
      process.env.CODEARTIFACT_AUTH_TOKEN = await fetchToken(client, cfg);
      logger.info("codeartifact_token_refreshed");
    } catch (err) {
      logger.error({ err }, "codeartifact_token_refresh_failed");
    }
  }, REFRESH_INTERVAL_MS);

  return () => clearInterval(interval);
}
