import fs from 'fs';
import path from 'path';
import type { SettlementRecord } from '@dbis/settlement-core';
import { settlementStoreSubdir } from '../config';

const baseDir =
  process.env.SETTLEMENT_STORE_DIR ||
  path.resolve(__dirname, '../../../data/settlement-store');

function storeDir(): string {
  const dir = path.join(baseDir, settlementStoreSubdir());
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
  return dir;
}

export class SettlementStore {
  save(record: SettlementRecord): void {
    const dir = storeDir();
    fs.writeFileSync(path.join(dir, `${record.settlementId}.json`), JSON.stringify(record, null, 2));
    fs.writeFileSync(path.join(dir, `key-${record.idempotencyKey}.json`), record.settlementId);
  }

  getById(id: string): SettlementRecord | null {
    const p = path.join(storeDir(), `${id}.json`);
    if (!fs.existsSync(p)) return null;
    return JSON.parse(fs.readFileSync(p, 'utf8')) as SettlementRecord;
  }

  getByIdempotencyKey(key: string): SettlementRecord | null {
    const ref = path.join(storeDir(), `key-${key}.json`);
    if (!fs.existsSync(ref)) return null;
    const id = fs.readFileSync(ref, 'utf8').trim();
    return this.getById(id);
  }

  list(limit = 50): SettlementRecord[] {
    const dir = storeDir();
    return fs
      .readdirSync(dir)
      .filter((f) => f.endsWith('.json') && !f.startsWith('key-'))
      .slice(0, limit)
      .map((f) => JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')) as SettlementRecord);
  }
}

export const settlementStore = new SettlementStore();
