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 normalizes HTTP to HTTPS for auth data lookups
 */
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://");
  }

  async get(saleorApiUrl: string): Promise<AuthData | undefined> {
    const normalizedUrl = this.normalizeUrl(saleorApiUrl);
    console.log(`[NormalizingAPL] Looking up auth for: ${saleorApiUrl} -> ${normalizedUrl}`);
    return this.apl.get(normalizedUrl);
  }

  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,
});