package com.zioinfo.mall.delivery;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.delivery.mapper.DeliveryMapper;
import com.zioinfo.mall.order.OrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

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

/**
 * 배송 API — /api/mall/delivery.
 *
 * <p>송장 등록·상태 변경은 운영(MANAGER+). 주문별 배송 조회는 주문 소유 고객.
 * 배송 상태가 DELIVERED 되면 주문 상태도 SHIPPED→DELIVERED 로 연동.
 */
@RestController
@RequestMapping("/api/mall/delivery")
@RequiredArgsConstructor
public class DeliveryController {

    private final DeliveryMapper mapper;
    private final OrderService orderService;

    @GetMapping("/order/{orderId}")
    public ApiResponse<MallDelivery> byOrder(@PathVariable Long orderId, Authentication auth) {
        orderService.detail(orderId, auth.getName(), isAdmin(auth));
        return ApiResponse.ok(mapper.findByOrderId(orderId));
    }

    @GetMapping
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallDelivery>> list(@RequestParam(required = false) String status,
                                                @RequestParam(defaultValue = "200") int limit) {
        return ApiResponse.ok(mapper.findAll(status, limit));
    }

    /** 송장 등록(출고) — 주문 PREPARING→SHIPPED 연동. */
    @PostMapping
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallDelivery> create(@RequestBody MallDelivery d, Authentication auth) {
        d.setStatus("IN_TRANSIT");
        mapper.insert(d);
        try { orderService.transition(d.getOrderId(), auth.getName(), true, "SHIPPED"); } catch (Exception ignored) {}
        return ApiResponse.ok(mapper.findById(d.getId()));
    }

    @PutMapping("/{id}/status")
    @PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallDelivery> status(@PathVariable Long id, @RequestBody Map<String, String> req, Authentication auth) {
        String to = req.get("status");
        mapper.updateStatus(id, to);
        if ("DELIVERED".equals(to)) {
            MallDelivery d = mapper.findById(id);
            try { orderService.transition(d.getOrderId(), auth.getName(), true, "DELIVERED"); } catch (Exception ignored) {}
        }
        return ApiResponse.ok(mapper.findById(id));
    }

    private boolean isAdmin(Authentication auth) {
        return auth.getAuthorities().stream()
                .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN") || a.getAuthority().equals("ROLE_MANAGER"));
    }
}
