import { Injectable } from '@angular/core';
import { BootstrapConfig } from '../../../shared/models/config';

const DRAFT_STORAGE_KEY = 'projectEditor.draftBootstrap.v1';
const DRAFT_SAVED_AT_KEY = 'projectEditor.draftSavedAt.v1';

interface StoredDraft {
  tenantId: string;
  bootstrap: BootstrapConfig;
  savedAt: number;
}

@Injectable({ providedIn: 'root' })
export class ProjectEditorDraftStorageService {
  save(bootstrap: BootstrapConfig): number {
    const savedAt = Date.now();
    const payload: StoredDraft = { tenantId: bootstrap.tenant.id, bootstrap, savedAt };
    try {
      localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(payload));
      localStorage.setItem(DRAFT_SAVED_AT_KEY, String(savedAt));
    } catch {
      // storage unavailable (private mode / quota) - draft simply won't persist
    }
    return savedAt;
  }

  load(tenantId: string): { bootstrap: BootstrapConfig; savedAt: number } | null {
    try {
      const raw = localStorage.getItem(DRAFT_STORAGE_KEY);
      if (!raw) {
        return null;
      }
      const parsed = JSON.parse(raw) as StoredDraft;
      if (parsed.tenantId !== tenantId) {
        return null;
      }
      return { bootstrap: parsed.bootstrap, savedAt: parsed.savedAt };
    } catch {
      return null;
    }
  }

  clear(): void {
    try {
      localStorage.removeItem(DRAFT_STORAGE_KEY);
      localStorage.removeItem(DRAFT_SAVED_AT_KEY);
    } catch {
      // ignore
    }
  }
}
