package com.nanri.aiimage.modules.task.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.config.ModuleCleanupProperties;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ModuleHistoryCleanupService {

    private final ModuleCleanupProperties moduleCleanupProperties;
    private final FileTaskMapper fileTaskMapper;
    private final FileResultMapper fileResultMapper;

    @Transactional
    @Scheduled(cron = "${aiimage.module-cleanup.cron:0 0 0 * * *}")
    public void cleanupConfiguredModules() {
        if (!moduleCleanupProperties.isEnabled()) {
            return;
        }
        List<String> moduleTypes = moduleCleanupProperties.getModuleTypes();
        if (moduleTypes == null || moduleTypes.isEmpty()) {
            return;
        }

        int deletedResults = fileResultMapper.delete(new LambdaQueryWrapper<FileResultEntity>()
                .in(FileResultEntity::getModuleType, moduleTypes));

        int resetTasks = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
                .in(FileTaskEntity::getModuleType, moduleTypes)
                .set(FileTaskEntity::getResultJson, null)
                .set(FileTaskEntity::getRequestJson, null)
                .set(FileTaskEntity::getErrorMessage, null));

        int deletedTasks = fileTaskMapper.delete(new LambdaQueryWrapper<FileTaskEntity>()
                .in(FileTaskEntity::getModuleType, moduleTypes));

        log.info("模块历史清理完成: moduleTypes={}, deletedResults={}, resetTasks={}, deletedTasks={}", moduleTypes, deletedResults, resetTasks, deletedTasks);
    }
}
