// lib/tools/adapters/mines/tabular-load.js
//
// Worker handler for the `mines.load_tabular` heartbeat task. Reads a queued
// source document, detects whether it holds assay samples or drill holes, runs
// the matching loader, and updates extraction_status. Numbers land in SQL
// (mines_assay_samples / mines_drill_holes) — never in document chunks.
//
// Called directly by the heartbeat worker (the bulk import that enqueued it was
// already approval-gated). No external network calls.

import { getDb, nowIso } from '../../../db.js';
import { detectTabularType, loadAssaySamples, loadDrillHoles } from '../../../mines/tabular-loaders.js';

/**
 * @param {object} input - { source_document_id }
 * @returns {Promise<object>} { status, tabular_type, rows_loaded, rows_skipped, unrecognized_columns? }
 */
export async function minesTabularLoad(input, options = {}) {
  const id = input?.source_document_id;
  if (!id) return { status: 'error', error: 'source_document_id_required' };

  const db = getDb();
  const doc = db.prepare(
    'SELECT id, project_id, original_path, file_type FROM mines_source_documents WHERE id = ?'
  ).get(id);
  if (!doc) return { status: 'error', error: 'source_document_not_found' };

  const setStatus = (status, err) => db.prepare(
    'UPDATE mines_source_documents SET extraction_status = ?, extraction_error = ?, updated_at = ? WHERE id = ?'
  ).run(status, err || null, nowIso(), id);

  setStatus('extracting', null);

  let type;
  try {
    type = await detectTabularType(doc.original_path);
  } catch (err) {
    setStatus('failed', 'tabular_read_error:' + (err?.message || ''));
    return { status: 'failed', error: 'read_error' };
  }

  if (type === 'assay') {
    const r = await loadAssaySamples(doc.original_path, doc.project_id, doc.id);
    if (r.status === 'error') { setStatus('failed', r.error); return { status: 'failed', tabular_type: 'assay', error: r.error }; }
    setStatus('complete', null);
    return { status: 'complete', tabular_type: 'assay', rows_loaded: r.rows_loaded, rows_skipped: r.rows_skipped, unrecognized_columns: r.unrecognized_columns };
  }

  if (type === 'drill') {
    const r = await loadDrillHoles(doc.original_path, doc.project_id, doc.id);
    if (r.status === 'error') { setStatus('failed', r.error); return { status: 'failed', tabular_type: 'drill', error: r.error }; }
    setStatus('complete', null);
    return { status: 'complete', tabular_type: 'drill', rows_loaded: r.rows_loaded, rows_skipped: r.rows_skipped };
  }

  // Neither signature matched — keep the row but record it as skipped.
  setStatus('skipped', 'unrecognized_tabular_type');
  return { status: 'skipped', tabular_type: 'unknown' };
}
