import axios from "axios";
import { logger } from "../utils/logger";

interface PlanResponse {
  data?: unknown;
  status?: number;
  error?: string;
}

export const loadPlanWithRetry = async (
  handle: string,
  retries = 3,
): Promise<PlanResponse> => {
  try {
    logger.log(`[Plan Service] Loading plan ${handle}, attempt 1/${retries}`);
    logger.log(
      `[Plan Service] Context: Deep link handle=${handle}, isClaimFlow=${handle.includes("claim")}`,
    );

    // Different endpoint if this is a claim flow
    const response = await loadPlan(handle);
    logger.log(`[Plan Service] Plan ${handle} loaded successfully:`, {
      status: response?.status,
      headers: response?.headers,
      data: response?.data,
    });

    return response;
  } catch (error: unknown) {
    logger.error(`[Plan Service] Error loading plan ${handle}:`, {
      message: (error as Error).message,
      status: (error as { response?: { status?: number } })?.response?.status,
      statusText: (error as { response?: { statusText?: string } })?.response
        ?.statusText,
      data: (error as { response?: { data?: unknown } })?.response?.data,
      headers: (error as { response?: { headers?: unknown } })?.response
        ?.headers,
      config: {
        url: (error as { config?: { url?: string } })?.config?.url,
        method: (error as { config?: { method?: string } })?.config?.method,
        baseURL: (error as { config?: { baseURL?: string } })?.config?.baseURL,
        headers: (error as { config?: { headers?: unknown } })?.config?.headers,
      },
    });

    if (retries > 1) {
      logger.log(
        `[Plan Service] Retrying plan ${handle}, ${retries - 1} attempts remaining`,
      );
      await new Promise((resolve) => setTimeout(resolve, 1000));
      return loadPlanWithRetry(handle, retries - 1);
    }

    return {
      error: `Failed to load plan ${handle} after ${4 - retries} attempts: ${(error as Error).message}`,
      status: (error as { response?: { status?: number } })?.response?.status,
    };
  }
};

export const loadPlan = async (handle: string): Promise<PlanResponse> => {
  logger.log(`[Plan Service] Making API request for plan ${handle}`);

  const endpoint = handle.includes("claim")
    ? `/api/claims/${handle}`
    : `/api/plans/${handle}`;

  logger.log(`[Plan Service] Using endpoint: ${endpoint}`);

  try {
    const response = await axios.get(endpoint);
    return response;
  } catch (error: unknown) {
    logger.error(`[Plan Service] API request failed for ${handle}:`, {
      endpoint,
      error: (error as Error).message,
      response: (error as { response?: { data?: unknown } })?.response?.data,
    });
    throw error;
  }
};
