package com.erp.tenant.service.stock.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.tenant.entity.stock.Stock;
import com.erp.tenant.entity.stock.StockAlert;
import com.erp.tenant.repository.stock.StockRepository;
import com.erp.tenant.service.stock.StockService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 租户端库存服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StockServiceImpl implements StockService {

    private final StockRepository stockRepository;
    private static final int DEFAULT_GLOBAL_THRESHOLD = 10;

    @Override
    public IPage<Stock> getStockPage(Long tenantId, Long warehouseId, int page, int pageSize) {
        return stockRepository.findPage(new Page<>(page, pageSize), tenantId, warehouseId);
    }

    @Override
    public IPage<Stock> getAlertPage(Long tenantId, Long warehouseId, String keyword,
                                      String alertLevel, int page, int pageSize) {
        return stockRepository.findAlertPage(
                new Page<>(page, pageSize),
                tenantId, warehouseId, keyword, alertLevel, DEFAULT_GLOBAL_THRESHOLD
        );
    }

    @Override
    public StockAlertSummary getAlertSummary(Long tenantId) {
        StockAlertSummary summary = new StockAlertSummary();
        summary.globalThreshold = DEFAULT_GLOBAL_THRESHOLD;

        Long critical = stockRepository.countOutOfStock(tenantId, null);
        Long warning = stockRepository.countLowStock(tenantId, null);

        summary.critical = critical != null ? critical : 0L;
        summary.warning = warning != null ? warning : 0L;
        summary.total = summary.critical + summary.warning;
        return summary;
    }

    @Override
    public Stock getStockDetail(Long tenantId, Long stockId) {
        return stockRepository.findById(stockId, tenantId);
    }

    @Override
    @Transactional
    public boolean freezeStock(Long tenantId, Long warehouseId, String skuCode,
                                Integer quantity, Long orderId) {
        Stock stock = stockRepository.findByWarehouseAndSku(warehouseId, skuCode, tenantId);
        if (stock == null) {
            log.warn("库存不存在: warehouseId={}, skuCode={}", warehouseId, skuCode);
            return false;
        }
        // TODO: update locked_quantity
        return true;
    }

    @Override
    @Transactional
    public boolean unfreezeStock(Long tenantId, Long warehouseId, String skuCode,
                                  Integer quantity, Long orderId) {
        Stock stock = stockRepository.findByWarehouseAndSku(warehouseId, skuCode, tenantId);
        if (stock == null) {
            return false;
        }
        // TODO: release locked_quantity
        return true;
    }
}
