import { readFile } from "node:fs/promises"
import { basename } from "node:path"
import { AgentConfig, AgentHeartbeat, NextScanJobResponse, ScanResult } from "./types.js"

export class FedeoApi {
    constructor(private readonly config: AgentConfig) {}

    private url(path: string) {
        return `${this.config.fedeoUrl}${path}`
    }

    private headers(extra?: HeadersInit): HeadersInit {
        return {
            "X-Agent-Token": this.config.agentToken,
            ...extra,
        }
    }

    private async request<T>(path: string, init: RequestInit = {}): Promise<T> {
        const response = await fetch(this.url(path), {
            ...init,
            headers: this.headers(init.headers),
        })

        if (!response.ok) {
            const body = await response.text().catch(() => "")
            throw new Error(`${init.method || "GET"} ${path} fehlgeschlagen: ${response.status} ${body}`)
        }

        return await response.json() as T
    }

    heartbeat(payload: AgentHeartbeat) {
        return this.request<{ status: string; pendingScanJobs: number }>("/instance-agent/heartbeat", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload),
        })
    }

    nextScanJob() {
        return this.request<NextScanJobResponse>("/instance-agent/scan-jobs/next")
    }

    updateScanJobStatus(jobId: string, status: "running" | "failed" | "canceled", message?: string) {
        return this.request(`/instance-agent/scan-jobs/${jobId}/status`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ status, message }),
        })
    }

    async uploadScan(jobId: string, result: ScanResult) {
        const form = new FormData()
        const fileBuffer = await readFile(result.path)
        const file = new File([fileBuffer], result.filename || basename(result.path), {
            type: result.mimeType,
        })

        form.append("file", file)

        return this.request(`/instance-agent/scan-jobs/${jobId}/upload`, {
            method: "POST",
            body: form,
        })
    }
}
