package com.erp.inventory.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.common.core.model.PageResponse;
import com.erp.inventory.dto.*;
import com.erp.inventory.entity.Stock;
import com.erp.inventory.service.StockCheckService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 库存查询控制器 - 租户后台API
 * 路由: /api/stock
 * 
 * 此控制器提供租户后台所需的 /api/stock 端点
 * 对应PHP后台的库存查询功能
 */
@Slf4j
@RestController
@RequestMapping("/api/stock")
@RequiredArgsConstructor
public class TenantStockApiController {

    private final StockCheckService stockCheckService;

    /**
     * 库存列表
     * GET /api/stock
     */
    @GetMapping
    public ApiResponse<PageResponse<StockListItemDTO>> listStock(
            @RequestParam(required = false) Long tenantId,
            @RequestParam(required = false) String skuCode,
            @RequestParam(required = false) String skuName,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(required = false) Boolean lowStock,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer limit) {
        
        log.info("查询库存列表: tenantId={}, skuCode={}, skuName={}, warehouseId={}, lowStock={}, page={}, limit={}", 
                tenantId, skuCode, skuName, warehouseId, lowStock, page, limit);
        
        StockQueryDTO query = StockQueryDTO.builder()
                .skuCode(skuCode)
                .skuName(skuName)
                .warehouseId(warehouseId)
                .lowStock(lowStock)
                .page(page)
                .limit(limit)
                .build();
        
        try {
            PageResponse<StockListItemDTO> result = stockCheckService.listStocks(query);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 库存详情（按仓库+SKU）
     * GET /api/stock/show
     */
    @GetMapping("/show")
    public ApiResponse<StockDetailDTO> getStockDetail(
            @RequestParam(required = false) Long tenantId,
            @RequestParam String skuCode,
            @RequestParam Long warehouseId) {
        
        log.info("查询库存详情: tenantId={}, skuCode={}, warehouseId={}", tenantId, skuCode, warehouseId);
        
        try {
            StockDetailDTO result = stockCheckService.getStockDetail(skuCode, warehouseId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存详情失败: skuCode={}, warehouseId={}", skuCode, warehouseId, e);
            if (e.getMessage().contains("不存在")) {
                return ApiResponse.notFound(e.getMessage());
            }
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 库存预警列表
     * GET /api/stock/warning
     */
    @GetMapping("/warning")
    public ApiResponse<PageResponse<StockWarningDTO>> listStockWarnings(
            @RequestParam(required = false) Long tenantId,
            @RequestParam(required = false) Long warehouseId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "15") Integer limit) {
        
        log.info("查询库存预警列表: tenantId={}, warehouseId={}, page={}, limit={}", 
                tenantId, warehouseId, page, limit);
        
        try {
            PageResponse<StockWarningDTO> result = stockCheckService.listStockWarnings(warehouseId, page, limit);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取库存预警列表失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 检查可用库存
     * GET /api/stock/check
     */
    @GetMapping("/check")
    public ApiResponse<Map<String, Object>> checkStock(
            @RequestParam(required = false) Long tenantId,
            @RequestParam String skuCode,
            @RequestParam Long warehouseId) {
        
        log.info("检查可用库存: tenantId={}, skuCode={}, warehouseId={}", tenantId, skuCode, warehouseId);
        
        try {
            Integer available = stockCheckService.checkAvailableStock(skuCode, warehouseId);
            return ApiResponse.success(Map.of(
                    "skuCode", skuCode,
                    "warehouseId", warehouseId,
                    "availableQuantity", available != null ? available : 0
            ));
        } catch (Exception e) {
            log.error("检查可用库存失败: skuCode={}, warehouseId={}", skuCode, warehouseId, e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 库存数据一致性检查与修复
     * POST /api/stock/check-consistency
     */
    @PostMapping("/check-consistency")
    public ApiResponse<Map<String, Object>> checkAndFixStockConsistency(
            @RequestParam(required = false) Long tenantId) {
        
        log.info("库存数据一致性检查: tenantId={}", tenantId);
        
        try {
            StockCheckService.ConsistencyCheckResult result = stockCheckService.checkAndFixStockConsistency();
            return ApiResponse.success(Map.of(
                    "checked", result.checked(),
                    "fixed", result.fixed(),
                    "errors", result.errors()
            ));
        } catch (Exception e) {
            log.error("库存一致性检查失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ApiResponse<String> health() {
        return ApiResponse.success("Stock API is healthy", null);
    }
}
