package cn.reghao.tnb.content.app.mall.controller;

import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.common.auth.AuthUser;
import cn.reghao.tnb.common.auth.UserContext;
import cn.reghao.tnb.content.app.mall.model.dto.CartDto;
import cn.reghao.tnb.content.app.mall.model.dto.BuyProductDto;
import cn.reghao.tnb.content.app.mall.model.vo.CartCard;
import cn.reghao.tnb.content.app.mall.service.BuyService;
import cn.reghao.tnb.content.app.mall.service.CartService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author reghao
 * @date 2024-04-16 10:54:44
 */
@Tag(name = "购物车接口")
@RestController
@RequestMapping("/api/mall/cart")
public class CartController {
    private final CartService cartService;
    private final BuyService buyService;

    public CartController(CartService cartService, BuyService buyService) {
        this.cartService = cartService;
        this.buyService = buyService;
    }

    @Operation(summary = "将商品加入购物车", description = "N")
    @AuthUser
    @PostMapping("")
    public String addCart(@RequestBody @Validated CartDto cartDto) {
        long loginUser = UserContext.getUserId();
        long itemId = cartDto.getItemId();
        int num = cartDto.getNum();
        cartService.addCartItem(loginUser, itemId, num);
        return WebResult.success();
    }

    @Operation(summary = "从购物车中删除商品", description = "N")
    @AuthUser
    @DeleteMapping("/{itemId}")
    public String deleteItem(@PathVariable("itemId") Long itemId) {
        long loginUser = UserContext.getUserId();
        cartService.deleteCartItem(loginUser, itemId);
        return WebResult.success();
    }

    @Operation(summary = "获取购物车中的商品", description = "N")
    @AuthUser
    @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getCartItems() {
        long loginUser = UserContext.getUserId();
        List<CartCard> list = cartService.getUserCart(loginUser);
        return WebResult.success(list);
    }

    @Operation(summary = "购买购物车商品", description = "N")
    @PostMapping("/buy")
    public String buyCartItems(@RequestBody @Validated BuyProductDto buyProductDto) {
        long orderId = buyService.buyCartItems(buyProductDto);
        return WebResult.success(orderId);
    }
}
