const axios = require('axios');

const BASE_URL = process.env.BASEROW_API_URL;
const TOKEN    = process.env.BASEROW_TOKEN;
const TABLE_MARCHES  = process.env.BASEROW_TABLE_MARCHES;
const TABLE_PIPELINE = process.env.BASEROW_TABLE_PIPELINE;

const client = axios.create({
  baseURL: BASE_URL,
  headers: { Authorization: `Token ${TOKEN}` },
});

// Récupère toutes les lignes d'une table (gestion pagination)
async function fetchAllRows(tableId, filters = {}) {
  const rows = [];
  let page = 1;
  let hasMore = true;

  while (hasMore) {
    const { data } = await client.get(`/database/rows/table/${tableId}/`, {
      params: { page, size: 200, user_field_names: true, ...filters },
    });
    rows.push(...data.results);
    hasMore = data.next !== null;
    page++;
  }

  return rows;
}

// Récupère une seule ligne par ID
async function fetchRow(tableId, rowId) {
  const { data } = await client.get(
    `/database/rows/table/${tableId}/${rowId}/`,
    { params: { user_field_names: true } }
  );
  return data;
}

module.exports = {
  getMarches:  (filters) => fetchAllRows(TABLE_MARCHES, filters),
  getMarcheById: (id)    => fetchRow(TABLE_MARCHES, id),
  getPipeline: (filters) => fetchAllRows(TABLE_PIPELINE, filters),
};
