package com.zioinfo.mall.inventory;

import com.zioinfo.mall.admin.AuditService;
import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.inventory.mapper.StoreInventoryMapper;
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;

/**
 * 매장별 당일 재고 ON/OFF API — /api/mall/store-inventory.
 * 관리자앱 '원터치' 토글. StoreManager는 자기 매장만(서비스 가드는 호출자 검증 권장).
 */
@RestController
@RequestMapping("/api/mall/store-inventory")
@RequiredArgsConstructor
@PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
public class StoreInventoryController {

    private final StoreInventoryMapper mapper;
    private final AuditService auditService;

    /** 매장별 마스터 상품 리스트(토글 화면). */
    @GetMapping("/store/{storeId}")
    public ApiResponse<List<MallStoreInventory>> byStore(@PathVariable Long storeId) {
        return ApiResponse.ok(mapper.findByStore(storeId));
    }

    /** 원터치 ON/OFF 토글 — OFF 시 해당 지역 온라인 즉시 품절. */
    @PutMapping("/store/{storeId}/product/{productId}/toggle")
    public ApiResponse<MallStoreInventory> toggle(@PathVariable Long storeId, @PathVariable Long productId,
                                                  @RequestBody Map<String, Boolean> req, Authentication auth) {
        boolean available = req.getOrDefault("available", true);
        mapper.setAvailable(storeId, productId, available, auth.getName());
        auditService.log(auth.getName(), "STORE_INV_TOGGLE",
                "store=" + storeId + ",product=" + productId, available ? "ON" : "OFF");
        return ApiResponse.ok(mapper.findOne(storeId, productId));
    }

    /** 재고 수량 조정. */
    @PutMapping("/store/{storeId}/product/{productId}/adjust")
    public ApiResponse<MallStoreInventory> adjust(@PathVariable Long storeId, @PathVariable Long productId,
                                                  @RequestBody Map<String, Integer> req) {
        mapper.adjustOnHand(storeId, productId, req.getOrDefault("delta", 0));
        return ApiResponse.ok(mapper.findOne(storeId, productId));
    }

    @PostMapping("/upsert")
    public ApiResponse<MallStoreInventory> upsert(@RequestBody MallStoreInventory si, Authentication auth) {
        si.setUpdatedBy(auth.getName());
        mapper.upsert(si);
        return ApiResponse.ok(mapper.findOne(si.getStoreId(), si.getProductId()));
    }
}
