import { config } from "./config.js";
import { createLogger } from "./logger.js";
import { getRuntimeSettings } from "./runtimeSettings.js";

const logger = createLogger(config.logLevel);

export class PaperlessClient {
  get isConfigured() {
    const { paperlessBaseUrl, paperlessToken } = getRuntimeSettings();
    return Boolean(paperlessBaseUrl && paperlessToken);
  }

  private buildUrl(path: string) {
    const { paperlessBaseUrl } = getRuntimeSettings();
    if (!paperlessBaseUrl) {
      throw new Error("Paperless base URL is not configured");
    }
    const trimmedBase = paperlessBaseUrl.replace(/\/+$/, "");
    const trimmedPath = path.replace(/^\/+/, "");
    return `${trimmedBase}/${trimmedPath}`;
  }

  private getHeaders(): HeadersInit {
    const headers: Record<string, string> = {
      Accept: "application/json"
    };
    const { paperlessToken } = getRuntimeSettings();
    if (paperlessToken) {
      headers.Authorization = `Token ${paperlessToken}`;
    }
    return headers;
  }

  async getDocument(documentId: number): Promise<Record<string, unknown> | null> {
    if (!this.isConfigured) {
      throw new Error("Paperless integration is not configured");
    }

    const url = this.buildUrl(`/api/documents/${documentId}/`);
    const response = await fetch(url, { headers: this.getHeaders() });

    if (response.status === 404) {
      return null;
    }

    if (!response.ok) {
      const text = await response.text();
      logger.error(`Paperless API error ${response.status}: ${text}`);
      throw new Error(`Paperless request failed with status ${response.status}`);
    }

    return response.json() as Promise<Record<string, unknown>>;
  }

  async searchDocuments(query: string, page = 1): Promise<Record<string, unknown>> {
    if (!this.isConfigured) {
      throw new Error("Paperless integration is not configured");
    }

    const url = new URL(this.buildUrl("/api/documents/"));
    url.searchParams.set("query", query);
    url.searchParams.set("page", page.toString());

    const response = await fetch(url, { headers: this.getHeaders() });

    if (!response.ok) {
      const text = await response.text();
      logger.error(`Paperless API error ${response.status}: ${text}`);
      throw new Error(`Paperless request failed with status ${response.status}`);
    }

    return response.json() as Promise<Record<string, unknown>>;
  }
}

export const paperlessClient = new PaperlessClient();
