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

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snack.server.common.Result;
import com.snack.server.module.order.dto.req.OrderPageReq;
import com.snack.server.module.order.dto.req.OrderSubmitReq;
import com.snack.server.module.order.service.OrderService;
import com.snack.server.module.order.vo.OrderDetailVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 订单（用户端）
 */
@Tag(name = "订单")
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService orderService;

    @Operation(summary = "提交订单")
    @SaCheckLogin
    @PostMapping
    public Result<Map<String, String>> submit(@Valid @RequestBody OrderSubmitReq req) {
        String orderNo = orderService.submitOrder(req);
        return Result.ok(Map.of("orderNo", orderNo));
    }

    @Operation(summary = "订单详情")
    @SaCheckLogin
    @GetMapping("/{id}")
    public Result<OrderDetailVO> detail(@Parameter(description = "订单 ID") @PathVariable Long id) {
        return Result.ok(orderService.getDetailByCurrentUser(id));
    }

    @Operation(summary = "我的订单（按状态筛选）")
    @SaCheckLogin
    @GetMapping
    public Result<Page<OrderDetailVO>> page(OrderPageReq req) {
        return Result.ok(orderService.pageCurrentUserOrders(req));
    }

    @Operation(summary = "支付订单（测试用模拟支付）")
    @SaCheckLogin
    @PostMapping("/{id}/pay")
    public Result<Void> pay(@Parameter(description = "订单 ID") @PathVariable Long id) {
        orderService.payOrder(id);
        return Result.ok();
    }

    @Operation(summary = "取消订单")
    @SaCheckLogin
    @PostMapping("/{id}/cancel")
    public Result<Void> cancel(@Parameter(description = "订单 ID") @PathVariable Long id) {
        orderService.cancelOrder(id);
        return Result.ok();
    }

    @Operation(summary = "确认收货")
    @SaCheckLogin
    @PostMapping("/{id}/receive")
    public Result<Void> receive(@Parameter(description = "订单 ID") @PathVariable Long id) {
        orderService.confirmReceive(id);
        return Result.ok();
    }

    @Operation(summary = "申请退款（需传入退款原因）")
    @SaCheckLogin
    @PostMapping("/{id}/refund")
    public Result<Void> refund(
            @Parameter(description = "订单 ID") @PathVariable Long id,
            @Parameter(description = "退款原因") @RequestParam(required = false, defaultValue = "用户申请退款") String reason) {
        orderService.applyRefund(id, reason);
        return Result.ok();
    }
}
