package com.snack.server.module.product.controller;

import cn.hutool.core.util.StrUtil;
import com.snack.server.common.Result;
import com.snack.server.module.product.service.ProductService;
import com.snack.server.module.product.vo.ProductDetailVO;
import com.snack.server.module.product.vo.ProductListVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 商品（用户端 / 公开）
 */
@Tag(name = "商品（公开）")
@RestController
@RequestMapping("/api/product")
@RequiredArgsConstructor
public class ProductPublicController {

    private final ProductService productService;

    @Operation(summary = "商品详情（用户端）")
    @GetMapping("/{id}")
    public Result<ProductDetailVO> detail(@Parameter(description = "商品 ID") @PathVariable Long id) {
        // 增加浏览量
        productService.incrViewCount(id);
        return Result.ok(productService.getDetail(id));
    }

    @Operation(summary = "分类下的商品列表（用户端分类页）")
    @GetMapping("/list")
    public Result<List<ProductListVO>> list(
            @Parameter(description = "分类 ID（多个用逗号分隔）") @RequestParam String categoryIds,
            @Parameter(description = "排序：sales_desc / price_asc / price_desc / create_desc")
            @RequestParam(required = false) String orderBy,
            @Parameter(description = "返回数量限制") @RequestParam(defaultValue = "20") Integer limit) {
        List<Long> ids = Arrays.stream(categoryIds.split(","))
                .filter(StrUtil::isNotBlank)
                .map(Long::valueOf)
                .toList();
        return Result.ok(productService.listByCategoryIds(ids, orderBy, limit));
    }

    @Operation(summary = "热门商品（is_hot=1，按销量倒序）")
    @GetMapping("/hot")
    public Result<List<ProductListVO>> hot(@RequestParam(defaultValue = "10") Integer limit) {
        return Result.ok(productService.listHotProducts(limit));
    }

    @Operation(summary = "新品上市（is_new=1，按 id 倒序）")
    @GetMapping("/new")
    public Result<List<ProductListVO>> newProducts(@RequestParam(defaultValue = "10") Integer limit) {
        return Result.ok(productService.listNewProducts(limit));
    }
}
