import { Category, Product, SortOption } from '@/domain/entities';
import {
  CatalogDomainService,
  CategoryFilter,
} from '@/domain/services/CatalogDomainService';
import { IProductRepository } from '@/application/ports/IProductRepository';
import { LocalizeProductUseCase } from './LocalizeProduct';
import { LocalizedProduct } from '@/application/dtos/LocalizedProduct';

export interface FilterProductsInput {
  category: CategoryFilter;
  searchQuery: string;
  sortBy: SortOption;
}

/**
 * USE CASE — Shop page: load, filter, sort, localize products
 */
export class FilterProductsUseCase {
  constructor(
    private readonly products: IProductRepository,
    private readonly localize: LocalizeProductUseCase
  ) {}

  execute(input: FilterProductsInput): LocalizedProduct[] {
    const all = this.products.findAll();
    const searchIndex = all.map((product) => {
      const localized = this.localize.execute(product);
      return {
        product,
        name: localized.name,
        description: localized.description,
      };
    });

    const filtered = CatalogDomainService.filterAndSort({
      products: all,
      category: input.category,
      searchQuery: input.searchQuery,
      sortBy: input.sortBy,
      searchIndex,
    });

    return this.localize.executeMany(filtered);
  }

  static parseCategory(value: string | null): CategoryFilter {
    return CatalogDomainService.parseCategory(value);
  }

  static readonly CATEGORIES: Category[] = CatalogDomainService.CATEGORIES;
}