import fs from "node:fs/promises";
import path from "node:path";
import type { ReviewSampleListResult, ReviewSamplesRepositoryPort, ReviewSamplePayload } from "./contracts.js";
import type { ReviewSampleRecord, SaveResultWithPath } from "../../src/types/global.js";

export class ReviewSamplesRepository implements ReviewSamplesRepositoryPort {
  private readonly filePath: string;

  constructor(userDataPath: string, fileName = "review-samples.jsonl") {
    this.filePath = path.join(userDataPath, fileName);
  }

  async list(limit = 50): Promise<ReviewSampleListResult> {
    try {
      const raw = await fs.readFile(this.filePath, "utf8");
      const lines = raw.split(/\r?\n/).filter(Boolean);
      const safeLimit = Math.max(1, Math.min(200, Number(limit) || 50));
      const samples = lines
        .slice(-safeLimit)
        .map((line) => {
          try {
            return JSON.parse(line) as ReviewSampleRecord;
          } catch {
            return null;
          }
        })
        .filter(Boolean) as ReviewSampleRecord[];
      return { ok: true, samples: samples.reverse(), total: lines.length, path: this.filePath };
    } catch {
      return { ok: true, samples: [], total: 0, path: this.filePath };
    }
  }

  async append(sample: ReviewSamplePayload): Promise<SaveResultWithPath> {
    await fs.mkdir(path.dirname(this.filePath), { recursive: true });
    await fs.appendFile(this.filePath, `${JSON.stringify({ savedAt: new Date().toISOString(), sample })}\n`, "utf8");
    return { ok: true, path: this.filePath };
  }
}
