import { DocumentFormatter } from '../utils/document-formatter.js';

export class DirectusClient {
    static API_BASE = 'https://api.ifuntanhub.dev';

    static itemsUrl(collection) {
        const params = new URLSearchParams({
            limit: '-1',
            fields: '*,file.id,file.filename_download,file.type,file.filename_disk',
        });

        return `${this.API_BASE}/items/${collection}?${params.toString()}`;
    }

    static fileId(file) {
        return file && typeof file === 'object' ? file.id : file;
    }

    static assetUrl(file) {
        return `${this.API_BASE}/assets/${this.fileId(file)}`;
    }

    static viewerUrl(item) {
        const type = DocumentFormatter.fileInfoFromItem(item).type;
        const params = new URLSearchParams({
            id: this.fileId(item.file),
            name: item.nama_berkas,
            type,
        });
        return `viewer.html?${params.toString()}`;
    }

    static async fetchPublished(collection) {
        const response = await fetch(this.itemsUrl(collection));
        if (!response.ok) throw new Error(`Gagal memuat koleksi ${collection}.`);
        const body = await response.json();
        const items = body.data || [];
        return items.filter(item => item.status === 'published');
    }
}
