import { Injectable, computed, signal } from '@angular/core';
import { SearchFilterState, SearchResult, SearchSuggestion } from '../models/search.model';
import { SearchState, createInitialSearchState } from '../models/search-state.model';

@Injectable({ providedIn: 'root' })
export class SearchStore {
  private readonly stateSignal = signal<SearchState>(createInitialSearchState());

  readonly state = this.stateSignal.asReadonly();
  readonly suggestions = computed(() => this.stateSignal().suggestions);
  readonly recentSearches = computed(() => this.stateSignal().recentSearches);
  readonly popularSearches = computed(() => this.stateSignal().popularSearches);

  patch(patch: Partial<SearchState>): void {
    this.stateSignal.update(current => ({ ...current, ...patch }));
  }

  setLoading(loading: boolean): void {
    this.patch({ loading });
  }

  setQuery(query: string): void {
    this.patch({ currentQuery: query, text: query });
  }

  setSuggestions(suggestions: SearchSuggestion[]): void {
    this.patch({ suggestions });
  }

  setResults(results: SearchResult | null): void {
    this.patch({
      results,
      totalResults: results?.total ?? 0,
      currentPage: results?.page ?? 1,
      page: results?.page ?? 1,
      pageSize: results?.pageSize ?? this.stateSignal().pageSize,
    });
  }

  setRecentSearches(items: string[]): void {
    this.patch({ recentSearches: items });
  }

  setPopularSearches(items: string[]): void {
    this.patch({ popularSearches: items });
  }

  setFilters(selectedFilters: SearchFilterState): void {
    this.patch({ selectedFilters, filters: selectedFilters });
  }
}
