import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LocalHistoryService {
  private readonly STORAGE_KEY = 'palm_oil_vault';

  saveRecord(result: any, filename: string, engine: string, imageData: string, dimensions: {width: number, height: number}): void {
    const history = this.getRecords();
    
    const newRecord = {
      timestamp: new Date().toLocaleString(),
      filename: filename,
      summary: JSON.stringify(result.industrial_summary), // Matches HistoryComponent's expectations
      inference_ms: result.inference_ms,
      engine: engine,
      detections: result.detections,
      imageData: imageData,
      dimensions: dimensions
    };

    history.unshift(newRecord); // Add newest to top
    // Limit history to 20 records to avoid localStorage overflow
    if (history.length > 20) {
      history.pop();
    }
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(history));
  }

  getRecords(): any[] {
    const data = localStorage.getItem(this.STORAGE_KEY);
    return data ? JSON.parse(data) : [];
  }

  /** Remove a single record by its unique timestamp+filename key */
  deleteRecord(timestamp: string, filename: string): void {
    const records = this.getRecords().filter(
      r => !(r.timestamp === timestamp && r.filename === filename)
    );
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(records));
  }

  clearAll(): void {
    localStorage.removeItem(this.STORAGE_KEY);
  }
}
