import { Injectable } from '@angular/core';
import { AdminDashboardActivityEntry, AdminDashboardActivityType } from '../models/admin-dashboard.model';

const HISTORY_STORAGE_KEY = 'adminDashboard.activityHistory.v1';
const MAX_ENTRIES = 20;

interface StoredHistory {
  tenantId: string;
  entries: AdminDashboardActivityEntry[];
}

/** Local publish/save activity log, scoped per tenant. Same localStorage pattern as ProjectEditorDraftStorageService - a real backend can later replace the read side without changing callers. */
@Injectable({ providedIn: 'root' })
export class AdminDashboardHistoryService {
  record(tenantId: string, type: AdminDashboardActivityType, timestamp: number): void {
    const entries = [
      { id: `${type}-${timestamp}`, type, timestamp },
      ...this.list(tenantId),
    ].slice(0, MAX_ENTRIES);

    this.persist(tenantId, entries);
  }

  list(tenantId: string): AdminDashboardActivityEntry[] {
    try {
      const raw = localStorage.getItem(HISTORY_STORAGE_KEY);
      if (!raw) {
        return [];
      }
      const parsed = JSON.parse(raw) as StoredHistory;
      return parsed.tenantId === tenantId ? parsed.entries : [];
    } catch {
      return [];
    }
  }

  private persist(tenantId: string, entries: AdminDashboardActivityEntry[]): void {
    try {
      const payload: StoredHistory = { tenantId, entries };
      localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(payload));
    } catch {
      // storage unavailable (private mode / quota) - history simply won't persist
    }
  }
}
