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

export interface SearchHistoryRepository {
  load(): string[];
  save(items: string[]): void;
  clear(): void;
}

const STORAGE_KEY = 'marketplace.search.feature.history';

@Injectable({ providedIn: 'root' })
export class LocalSearchHistoryRepository implements SearchHistoryRepository {
  load(): string[] {
    if (typeof window === 'undefined') {
      return [];
    }

    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) {
        return [];
      }

      const parsed = JSON.parse(raw);
      return Array.isArray(parsed)
        ? parsed.filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)
        : [];
    } catch {
      return [];
    }
  }

  save(items: string[]): void {
    if (typeof window === 'undefined') {
      return;
    }

    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
  }

  clear(): void {
    if (typeof window === 'undefined') {
      return;
    }

    localStorage.removeItem(STORAGE_KEY);
  }
}

@Injectable({ providedIn: 'root' })
export class BackendSearchHistoryRepository implements SearchHistoryRepository {
  load(): string[] {
    return [];
  }

  save(_items: string[]): void {
    // Placeholder for future backend endpoint.
  }

  clear(): void {
    // Placeholder for future backend endpoint.
  }
}
