package com.toyshop.controller;

import com.toyshop.dto.ApiResponse;
import com.toyshop.entity.Product;
import com.toyshop.repository.CarouselRepository;
import com.toyshop.repository.NoticeRepository;
import com.toyshop.repository.ProductRepository;
import com.toyshop.repository.CategoryRepository;
import com.toyshop.service.ProductService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/public")
public class PublicController {
  private final ProductService productService;
  private final CategoryRepository categoryRepository;
  private final ProductRepository productRepository;
  private final CarouselRepository carouselRepository;
  private final NoticeRepository noticeRepository;

  public PublicController(ProductService productService, CategoryRepository categoryRepository,
                          ProductRepository productRepository, CarouselRepository carouselRepository,
                          NoticeRepository noticeRepository) {
    this.productService = productService;
    this.categoryRepository = categoryRepository;
    this.productRepository = productRepository;
    this.carouselRepository = carouselRepository;
    this.noticeRepository = noticeRepository;
  }

  @GetMapping("/home")
  public ApiResponse<Map<String, Object>> home() {
    Map<String, Object> data = new HashMap<>();
    data.put("carousels", carouselRepository.findAllByOrderBySortOrderAsc());
    data.put("notices", noticeRepository.findAll());
    data.put("categories", categoryRepository.findAll());
    data.put("hot", productService.search(null, null, "sales"));
    data.put("newest", productService.search(null, null, null));
    return ApiResponse.ok(data);
  }

  @GetMapping("/products")
  public ApiResponse<?> products(@RequestParam(required = false) String keyword,
                                 @RequestParam(required = false) Long categoryId,
                                 @RequestParam(required = false) String sort) {
    return ApiResponse.ok(productService.search(keyword, categoryId, sort));
  }

  @GetMapping("/products/{id}")
  public ApiResponse<Map<String, Object>> productDetail(@PathVariable Long id) {
    Product product = productRepository.findById(id).orElseThrow();
    Map<String, Object> data = new HashMap<>();
    data.put("product", product);
    data.put("images", productService.getImages(product));
    return ApiResponse.ok(data);
  }
}
