package com.zioinfo.mall.review;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.review.mapper.ReviewMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/** 리뷰 API — /api/mall/review. GET 공개, 작성/삭제 인증 고객. */
@RestController
@RequestMapping("/api/mall/review")
@RequiredArgsConstructor
public class ReviewController {

    private final ReviewMapper mapper;

    @GetMapping("/product/{productId}")
    public ApiResponse<List<MallReview>> byProduct(@PathVariable Long productId,
                                                   @RequestParam(defaultValue = "50") int limit) {
        return ApiResponse.ok(mapper.findByProduct(productId, limit));
    }

    @GetMapping("/product/{productId}/stats")
    public ApiResponse<Map<String, Object>> stats(@PathVariable Long productId) {
        return ApiResponse.ok(mapper.stats(productId));
    }

    @PostMapping
    @Transactional
    public ApiResponse<MallReview> write(@RequestBody MallReview r, Authentication auth) {
        r.setAuthor(auth.getName());
        if (r.getRating() == null || r.getRating() < 1 || r.getRating() > 5) {
            throw new IllegalArgumentException("ERR-REV-400: 평점은 1~5");
        }
        mapper.insert(r);
        mapper.applyStats(r.getProductId());
        return ApiResponse.ok(mapper.findById(r.getId()));
    }

    @PutMapping("/{id}/helpful")
    public ApiResponse<String> helpful(@PathVariable Long id) {
        mapper.incHelpful(id);
        return ApiResponse.ok("ok");
    }

    @DeleteMapping("/{id}")
    @Transactional
    public ApiResponse<String> delete(@PathVariable Long id, Authentication auth) {
        MallReview r = mapper.findById(id);
        mapper.delete(id, auth.getName());
        if (r != null) mapper.applyStats(r.getProductId());
        return ApiResponse.ok("deleted");
    }
}
