package com.zioinfo.mall.cart;

import com.zioinfo.mall.cart.mapper.CartMapper;
import com.zioinfo.mall.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/** 장바구니 API — /api/mall/cart. owner=인증 사용자. */
@RestController
@RequestMapping("/api/mall/cart")
@RequiredArgsConstructor
public class CartController {

    private final CartMapper mapper;

    @GetMapping
    public ApiResponse<Map<String, Object>> list(Authentication auth) {
        List<MallCartItem> items = mapper.findByOwner(auth.getName());
        BigDecimal total = items.stream()
                .map(i -> (i.getUnitPrice() == null ? BigDecimal.ZERO : i.getUnitPrice())
                        .multiply(BigDecimal.valueOf(i.getQuantity() == null ? 0 : i.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String, Object> out = new LinkedHashMap<>();
        out.put("items", items);
        out.put("itemCount", items.size());
        out.put("totalAmount", total);
        return ApiResponse.ok(out);
    }

    @PostMapping
    public ApiResponse<MallCartItem> add(@RequestBody MallCartItem item, Authentication auth) {
        item.setOwner(auth.getName());
        if (item.getQuantity() == null || item.getQuantity() < 1) item.setQuantity(1);
        MallCartItem existing = mapper.findExisting(auth.getName(), item.getProductId(), item.getOptionId());
        if (existing != null) {
            int newQty = existing.getQuantity() + item.getQuantity();
            mapper.updateQty(existing.getId(), auth.getName(), newQty);
            return ApiResponse.ok(mapper.findById(existing.getId()));
        }
        mapper.insert(item);
        return ApiResponse.ok(item);
    }

    @PutMapping("/{id}")
    public ApiResponse<MallCartItem> updateQty(@PathVariable Long id, @RequestBody Map<String, Integer> req, Authentication auth) {
        int qty = req.getOrDefault("quantity", 1);
        if (qty < 1) throw new IllegalArgumentException("ERR-CART-400: 수량은 1 이상");
        mapper.updateQty(id, auth.getName(), qty);
        return ApiResponse.ok(mapper.findById(id));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> remove(@PathVariable Long id, Authentication auth) {
        mapper.delete(id, auth.getName());
        return ApiResponse.ok(null);
    }

    @DeleteMapping
    public ApiResponse<Void> clear(Authentication auth) {
        mapper.clear(auth.getName());
        return ApiResponse.ok(null);
    }
}
