package de.effigenix.infrastructure.inventory.scheduler;

import de.effigenix.application.inventory.CheckStockExpiry;
import de.effigenix.application.inventory.ExpiryCheckResult;
import de.effigenix.shared.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

@Component
@Profile("!no-db")
public class StockExpiryScheduler {

    private static final Logger logger = LoggerFactory.getLogger(StockExpiryScheduler.class);

    private final CheckStockExpiry checkStockExpiry;

    public StockExpiryScheduler(CheckStockExpiry checkStockExpiry) {
        this.checkStockExpiry = checkStockExpiry;
    }

    @Scheduled(cron = "${effigenix.inventory.expiry-check-cron:0 0 6 * * *}")
    public void checkExpiry() {
        logger.info("Starting stock expiry check");
        switch (checkStockExpiry.execute(LocalDate.now())) {
            case Result.Failure(var err) ->
                logger.error("Stock expiry check failed: {} - {}", err.code(), err.message());
            case Result.Success(ExpiryCheckResult result) -> {
                if (result.failedCount() > 0) {
                    logger.warn("Stock expiry check completed with failures: {} expired, {} expiring soon, {} failed",
                            result.expiredCount(), result.expiringSoonCount(), result.failedCount());
                } else {
                    logger.info("Stock expiry check completed: {} expired, {} expiring soon",
                            result.expiredCount(), result.expiringSoonCount());
                }
            }
        }
    }
}
