package com.jeesharp.business.modules.setting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jeesharp.business.modules.setting.entity.AppSplashAd;
import com.jeesharp.business.modules.setting.mapper.AppSplashAdMapper;
import com.jeesharp.business.modules.setting.service.AppSplashAdService;
import com.jeesharp.business.modules.setting.vo.AppSplashAdQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 开屏广告领域服务实现。
 *
 * @author jeesharp
 * @since 2026-04-21
 */
@Service
@Transactional(readOnly = true)
public class AppSplashAdServiceImpl extends CrudService<AppSplashAdMapper, AppSplashAd, AppSplashAdQueryVO> implements AppSplashAdService {

    private static final int DEFAULT_ENABLED_STATUS = 1;
    private static final int DEFAULT_SORT_ORDER = 0;
    private static final int DEFAULT_SKIPPABLE = 1;

    @Override
    public List<AppSplashAd> listActiveForClient(String platform) {
        if (platform == null || platform.isBlank()) {
            return List.of();
        }
        LocalDateTime now = LocalDateTime.now();
        LambdaQueryWrapper<AppSplashAd> w = new LambdaQueryWrapper<>();
        w.eq(AppSplashAd::getPlatform, platform.trim());
        w.eq(AppSplashAd::getStatus, 1);
        w.and(
                q -> q.isNull(AppSplashAd::getDisplayBegin)
                        .or()
                        .le(AppSplashAd::getDisplayBegin, now));
        w.and(
                q -> q.isNull(AppSplashAd::getDisplayEnd)
                        .or()
                        .ge(AppSplashAd::getDisplayEnd, now));
        w.orderByAsc(AppSplashAd::getSortOrder).orderByDesc(AppSplashAd::getUpdateDate);
        return this.list(w);
    }

    @Override
    @Transactional(readOnly = false)
    public void createSplashAd(AppSplashAd entity) {
        if (entity.getStatus() == null) {
            entity.setStatus(DEFAULT_ENABLED_STATUS);
        }
        if (entity.getSortOrder() == null) {
            entity.setSortOrder(DEFAULT_SORT_ORDER);
        }
        if (entity.getSkippable() == null) {
            entity.setSkippable(DEFAULT_SKIPPABLE);
        }
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateSplashAd(AppSplashAd entity) {
        update(entity);
    }

}
