const { getEnvConfig } = require('./config');

async function baserowFetch(endpoint, options = {}) {
    const { baserowUrl, baserowToken } = getEnvConfig();
    const url = `${baserowUrl}/api${endpoint}`;
    console.log(`[baserow] ${options.method || 'GET'} ${url}`);

    const headers = {
        Authorization: `Token ${baserowToken}`,
        ...(options.headers || {}),
    };
    if (options.body) {
        headers['Content-Type'] = 'application/json';
    }

    const res = await fetch(url, { ...options, headers });

    if (!res.ok) {
        const body = await res.text().catch(() => '');
        const msg = `Baserow ${res.status} ${res.statusText}: ${body.substring(0, 300)}`;
        console.error(`[baserow] ERROR: ${msg}`);
        throw new Error(msg);
    }
    return res.json();
}

async function listRows(tableId, filters = {}) {
    let all = [];
    let page = 1;
    while (true) {
        let url = `/database/rows/table/${tableId}/?user_field_names=true&size=200&page=${page}`;
        for (const [field, value] of Object.entries(filters)) {
            url += `&filter__${encodeURIComponent(field)}__equal=${encodeURIComponent(value)}`;
        }
        const data = await baserowFetch(url);
        console.log(`[baserow] Table ${tableId} page ${page}: ${(data.results || []).length} rows`);
        all = all.concat(data.results || []);
        if (!data.next) break;
        page++;
    }
    return all;
}

async function createRow(tableId, row) {
    console.log(`[baserow] Create row in table ${tableId}`);
    return baserowFetch(`/database/rows/table/${tableId}/?user_field_names=true`, {
        method: 'POST',
        body: JSON.stringify(row),
    });
}

async function batchCreateRows(tableId, rows) {
    if (!rows.length) return;
    console.log(`[baserow] Batch create ${rows.length} rows in table ${tableId}`);
    for (let i = 0; i < rows.length; i += 200) {
        const chunk = rows.slice(i, i + 200);
        await baserowFetch(`/database/rows/table/${tableId}/batch/?user_field_names=true`, {
            method: 'POST',
            body: JSON.stringify({ items: chunk }),
        });
    }
}

async function updateRow(tableId, rowId, data) {
    console.log(`[baserow] Update row ${rowId} in table ${tableId}`);
    return baserowFetch(`/database/rows/table/${tableId}/${rowId}/?user_field_names=true`, {
        method: 'PATCH',
        body: JSON.stringify(data),
    });
}

module.exports = { listRows, createRow, batchCreateRows, updateRow };