package com.zioinfo.mall.order;

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

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

/** 주문 API — /api/mall/order. 인증 고객. 관리자 목록은 MANAGER+. */
@RestController
@RequestMapping("/api/mall/order")
@RequiredArgsConstructor
public class OrderController {

    private final OrderService service;
    private final OrderMapper mapper;

    @GetMapping
    public ApiResponse<List<MallOrder>> myOrders(@RequestParam(required = false) String status, Authentication auth) {
        return ApiResponse.ok(service.myOrders(auth.getName(), status));
    }

    /** 전체 주문 목록 (운영) — MANAGER+. */
    @GetMapping("/admin")
    @org.springframework.security.access.prepost.PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallOrder>> allOrders(@RequestParam(required = false) String status,
                                                  @RequestParam(defaultValue = "200") int limit) {
        return ApiResponse.ok(mapper.findAll(status, limit));
    }

    /** 매장별 주문 (Live Order Dashboard — Fulfillment Time 정렬) — MANAGER+. */
    @GetMapping("/store/{storeId}")
    @org.springframework.security.access.prepost.PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<List<MallOrder>> storeOrders(@PathVariable Long storeId,
                                                    @RequestParam(required = false) String status,
                                                    @RequestParam(defaultValue = "200") int limit) {
        return ApiResponse.ok(mapper.findByStore(storeId, status, limit));
    }

    /** 제작완료 꽃사진(Proof of Quality) 업로드 → 고객 MMS 발송 — MANAGER+. */
    @PostMapping("/{id}/proof-photo")
    @org.springframework.security.access.prepost.PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallOrder> proofPhoto(@PathVariable Long id, @RequestBody Map<String, String> req, Authentication auth) {
        return ApiResponse.ok(service.attachProofPhoto(id, req.get("photoUrl"), auth.getName()));
    }

    /** 문앞사진(Proof of Delivery) 업로드 — MANAGER+. */
    @PostMapping("/{id}/pod-photo")
    @org.springframework.security.access.prepost.PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
    public ApiResponse<MallOrder> podPhoto(@PathVariable Long id, @RequestBody Map<String, String> req, Authentication auth) {
        return ApiResponse.ok(service.attachPodPhoto(id, req.get("photoUrl"), auth.getName()));
    }

    @GetMapping("/{id}")
    public ApiResponse<MallOrder> get(@PathVariable Long id, Authentication auth) {
        return ApiResponse.ok(service.detail(id, auth.getName(), isAdmin(auth)));
    }

    @PostMapping("/checkout")
    public ApiResponse<MallOrder> checkout(@RequestBody OrderService.CheckoutRequest req, Authentication auth) {
        return ApiResponse.ok(service.checkout(auth.getName(), req));
    }

    @PutMapping("/{id}/status")
    public ApiResponse<MallOrder> transition(@PathVariable Long id, @RequestBody Map<String, String> req, Authentication auth) {
        return ApiResponse.ok(service.transition(id, auth.getName(), isAdmin(auth), req.get("status")));
    }

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