// storage/actuals-store.ts — SPEC-287: Persistence for ActualRecord and CalibrationFactors
import { join } from 'node:path';
import { readJson, writeJson, projectDataDir } from './base-store.js';
import { withFileLock } from './file-mutex.js';
// ---------------------------------------------------------------------------
// Path helpers
// ---------------------------------------------------------------------------
function actualsPath(projectId) {
    return join(projectDataDir(projectId), 'actuals.json');
}
function calibrationPath(projectId) {
    return join(projectDataDir(projectId), 'calibration.json');
}
// ---------------------------------------------------------------------------
// ActualRecord CRUD
// ---------------------------------------------------------------------------
export async function listActuals(projectId) {
    return readJson(actualsPath(projectId), []);
}
export async function getActual(projectId, specId) {
    const records = await listActuals(projectId);
    return records.find((r) => r.specId === specId);
}
export async function saveActual(projectId, record) {
    const filePath = actualsPath(projectId);
    return withFileLock(filePath, async () => {
        const records = await readJson(filePath, []);
        const existingIdx = records.findIndex((r) => r.specId === record.specId);
        if (existingIdx >= 0) {
            records[existingIdx] = record;
        }
        else {
            records.push(record);
        }
        await writeJson(filePath, records);
        return record;
    });
}
export async function deleteActual(projectId, specId) {
    const filePath = actualsPath(projectId);
    return withFileLock(filePath, async () => {
        const records = await readJson(filePath, []);
        const filtered = records.filter((r) => r.specId !== specId);
        if (filtered.length === records.length) {
            return false;
        }
        await writeJson(filePath, filtered);
        return true;
    });
}
// ---------------------------------------------------------------------------
// CalibrationFactors CRUD
// ---------------------------------------------------------------------------
export async function getCalibration(projectId) {
    const data = await readJson(calibrationPath(projectId), null);
    return data;
}
export async function saveCalibration(projectId, factors) {
    await writeJson(calibrationPath(projectId), factors);
    return factors;
}
//# sourceMappingURL=actuals-store.js.map