import * as fs from 'fs';
import * as path from 'path';

export interface ScanState {
  lastScannedBlock: number;
  updatedAt: string;
}

export function loadScanState(filePath: string, defaultFrom: number): ScanState {
  try {
    const raw = fs.readFileSync(filePath, 'utf8');
    const parsed = JSON.parse(raw) as ScanState;
    if (typeof parsed.lastScannedBlock === 'number' && parsed.lastScannedBlock >= 0) {
      return parsed;
    }
  } catch {
    // fresh
  }
  return { lastScannedBlock: defaultFrom - 1, updatedAt: new Date().toISOString() };
}

export function saveScanState(filePath: string, state: ScanState): void {
  const dir = path.dirname(filePath);
  fs.mkdirSync(dir, { recursive: true });
  state.updatedAt = new Date().toISOString();
  fs.writeFileSync(filePath, JSON.stringify(state, null, 2));
}
