import { APL, AuthData } from "@saleor/app-sdk/APL";
import { SaleorApp } from "@saleor/app-sdk/saleor-app";
import { FileAPL } from "@saleor/app-sdk/APL/file";

/**
 * APL wrapper that:
 * 1. Normalizes HTTP to HTTPS for auth data lookups (for Cloudflare compatibility)
 * 2. Prefers SALEOR_API_URL env var over stored auth URL (for internal networking)
 */
class NormalizingAPL implements APL {
  private apl: FileAPL;

  constructor(config: { fileName: string }) {
    this.apl = new FileAPL(config);
  }

  private normalizeUrl(url: string): string {
    return url.replace(/^http:\/\//, "https://");
  }

  /**
   * Get auth data and optionally override saleorApiUrl with env var
   */
  async get(saleorApiUrl: string): Promise<AuthData | undefined> {
    const normalizedUrl = this.normalizeUrl(saleorApiUrl);
    console.log(`[NormalizingAPL] Looking up auth for: ${saleorApiUrl} -> ${normalizedUrl}`);
    
    const authData = await this.apl.get(normalizedUrl);
    
    if (!authData) {
      return undefined;
    }

    // If SALEOR_API_URL is set, prefer it over the stored URL
    // This enables internal networking (e.g., http://saleor-api.saleor:8000)
    // while still using the stored token for authentication
    if (process.env.SALEOR_API_URL) {
      console.log(`[NormalizingAPL] Using SALEOR_API_URL: ${process.env.SALEOR_API_URL} (env var overrides stored: ${authData.saleorApiUrl})`);
      return {
        ...authData,
        saleorApiUrl: process.env.SALEOR_API_URL,
      };
    }

    return authData;
  }

  async set(authData: AuthData): Promise<void> {
    const normalizedUrl = this.normalizeUrl(authData.saleorApiUrl);
    console.log(`[NormalizingAPL] Storing auth for: ${authData.saleorApiUrl} -> ${normalizedUrl}`);
    return this.apl.set({
      ...authData,
      saleorApiUrl: normalizedUrl,
    });
  }

  async delete(saleorApiUrl: string): Promise<void> {
    const normalizedUrl = this.normalizeUrl(saleorApiUrl);
    return this.apl.delete(normalizedUrl);
  }

  async getAll(): Promise<AuthData[]> {
    return this.apl.getAll();
  }
}

export let apl: APL;

switch (process.env.APL) {
  default:
    apl = new NormalizingAPL({
      fileName: process.env.AUTH_DATA_FILE_PATH || "/tmp/.auth-data.json",
    });
}

export const saleorApp = new SaleorApp({
  apl,
});