import { Injectable, inject } from '@angular/core';
import { AuthService } from '@marketplaces/auth';
import { SearchHistory } from '../models/search.model';
import { BackendSearchHistoryRepository, LocalSearchHistoryRepository, SearchHistoryRepository } from './search-history.repository';

@Injectable({ providedIn: 'root' })
export class SearchHistoryService {
  private readonly authService = inject(AuthService);
  private readonly localRepository = inject(LocalSearchHistoryRepository);
  private readonly backendRepository = inject(BackendSearchHistoryRepository);

  private readonly maxSize = 12;

  private get repository(): SearchHistoryRepository {
    return this.authService.session() ? this.backendRepository : this.localRepository;
  }

  getSnapshot(): SearchHistory {
    const items = this.repository.load();
    return {
      items,
      recent: items.slice(0, 8),
      popular: [],
    };
  }

  push(query: string, maxHistory = this.maxSize): SearchHistory {
    const normalized = query.trim();
    if (!normalized.length) {
      return this.getSnapshot();
    }

    const existing = this.repository.load();
    const next = [normalized, ...existing.filter(item => item.toLowerCase() !== normalized.toLowerCase())]
      .slice(0, Math.max(1, maxHistory));

    this.repository.save(next);
    return {
      items: next,
      recent: next.slice(0, 8),
      popular: [],
    };
  }

  clear(): SearchHistory {
    this.repository.clear();
    return { items: [], recent: [], popular: [] };
  }
}
