import type { FilyxResponse, FilyxSettings } from "../types";

const defaultBaseUrl = "https://filyx.fr";
const legacyBaseUrls = new Set([
  "https://filyx.hom3r-off.fr",
  "http://filyx.hom3r-off.fr",
]);

/**
 * FilyX moved from filyx.hom3r-off.fr to filyx.fr.  A POST redirect loses the
 * bearer token in Stream Deck, so old button settings must be migrated before
 * a request is made rather than relying on the web-server redirect.
 */
export function normalizeFilyxBaseUrl(value: unknown): string {
  const candidate = String(value || defaultBaseUrl).trim().replace(/\/+$/, "");
  return legacyBaseUrls.has(candidate.toLowerCase()) ? defaultBaseUrl : (candidate || defaultBaseUrl);
}

export class FilyxClient {
  private readonly baseUrl: string;
  private readonly apiKey: string;

  public constructor(settings: FilyxSettings) {
    this.baseUrl = normalizeFilyxBaseUrl(settings.apiUrl);
    this.apiKey = String(settings.apiKey || "").trim();
  }

  public async action(action: string, settings: Record<string, unknown>): Promise<FilyxResponse> {
    if (!this.apiKey.startsWith("fxsd_")) throw new Error("Liaison automatique FilyX en cours : termine la confirmation dans le navigateur.");
    const response = await fetch(`${this.baseUrl}/api/streamdeck/plugin/action`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": `Bearer ${this.apiKey}`, "Accept": "application/json" },
      body: JSON.stringify({ channel_id: Number(settings.channelId || 0) || undefined, action, settings })
    });
    const payload = await response.json().catch(() => ({ ok: false, error: "Réponse FilyX invalide." })) as FilyxResponse;
    if (!response.ok || payload.ok === false) throw new Error(payload.error || "FilyX a refusé l’action.");
    return payload;
  }

  public async bootstrap(channelId?: number): Promise<FilyxResponse> {
    if (!this.apiKey.startsWith("fxsd_")) throw new Error("Liaison automatique FilyX en cours : termine la confirmation dans le navigateur.");
    const suffix = channelId ? `?channel_id=${encodeURIComponent(String(channelId))}` : "";
    const response = await fetch(`${this.baseUrl}/api/streamdeck/plugin/bootstrap${suffix}`, {
      headers: { "Authorization": `Bearer ${this.apiKey}`, "Accept": "application/json" }
    });
    const payload = await response.json().catch(() => ({ ok: false, error: "Réponse FilyX invalide." })) as FilyxResponse;
    if (!response.ok || payload.ok === false) throw new Error(payload.error || "FilyX a refusé la synchronisation du thème.");
    return payload;
  }
}
