package com.zioinfo.mall.transfer;

import com.zioinfo.mall.admin.AuditService;
import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.inventory.mapper.StoreInventoryMapper;
import com.zioinfo.mall.transfer.mapper.TransferMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 매장간 재고 이양 API — /api/mall/transfer. MANAGER+.
 * 승인 시 from 매장 차감 + to 매장 증가(재고 이동). AI 추천은 ai 모듈에서 생성.
 */
@RestController
@RequestMapping("/api/mall/transfer")
@RequiredArgsConstructor
@PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
public class TransferController {

    private final TransferMapper mapper;
    private final StoreInventoryMapper storeInventoryMapper;
    private final AuditService auditService;

    @GetMapping
    public ApiResponse<List<MallTransfer>> list(@RequestParam(required = false) String status,
                                                @RequestParam(required = false) Long storeId) {
        return ApiResponse.ok(mapper.findAll(status, storeId));
    }

    @GetMapping("/{id}")
    public ApiResponse<MallTransfer> get(@PathVariable Long id) {
        return ApiResponse.ok(mapper.findById(id));
    }

    /** 이양 요청 발송. */
    @PostMapping
    public ApiResponse<MallTransfer> request(@RequestBody MallTransfer t, Authentication auth) {
        t.setRequestedBy(auth.getName());
        t.setStatus("REQUESTED");
        mapper.insert(t);
        auditService.log(auth.getName(), "TRANSFER_REQUEST",
                "from=" + t.getFromStoreId() + ",to=" + t.getToStoreId(), "product=" + t.getProductId() + " qty=" + t.getQuantity());
        return ApiResponse.ok(mapper.findById(t.getId()));
    }

    /** 승인 → 재고 이동(from 차감, to 증가). */
    @PutMapping("/{id}/approve")
    @Transactional
    public ApiResponse<MallTransfer> approve(@PathVariable Long id, Authentication auth) {
        MallTransfer t = mapper.findById(id);
        if (t == null) throw new RuntimeException("ERR-TRF-404: 이양 요청 없음");
        if (!"REQUESTED".equals(t.getStatus())) {
            throw new RuntimeException("ERR-TRF-409: 처리 가능한 상태가 아님(" + t.getStatus() + ")");
        }
        storeInventoryMapper.adjustOnHand(t.getFromStoreId(), t.getProductId(), -t.getQuantity());
        storeInventoryMapper.adjustOnHand(t.getToStoreId(), t.getProductId(), t.getQuantity());
        mapper.updateStatus(id, "COMPLETED", auth.getName());
        auditService.log(auth.getName(), "TRANSFER_APPROVE", String.valueOf(id), "moved=" + t.getQuantity());
        return ApiResponse.ok(mapper.findById(id));
    }

    @PutMapping("/{id}/reject")
    public ApiResponse<MallTransfer> reject(@PathVariable Long id, Authentication auth) {
        mapper.updateStatus(id, "REJECTED", auth.getName());
        return ApiResponse.ok(mapper.findById(id));
    }
}
