using Quartz;

namespace Service.Jobs;

/// <summary>
/// 日志清理定时任务
/// </summary>
[DisallowConcurrentExecution]
public class LogCleanupJob(ILogger<LogCleanupJob> logger) : IJob
{
    private const int RetentionDays = 30; // 保留30天的日志

    public Task Execute(IJobExecutionContext context)
    {
        try
        {
            logger.LogInformation("开始执行日志清理任务");

            var logDirectory = Path.Combine(Directory.GetCurrentDirectory(), "logs");
            if (!Directory.Exists(logDirectory))
            {
                logger.LogWarning("日志目录不存在: {LogDirectory}", logDirectory);
                return Task.CompletedTask;
            }

            var cutoffDate = DateTime.Now.AddDays(-RetentionDays);
            var logFiles = Directory.GetFiles(logDirectory, "log-*.txt");
            var deletedCount = 0;

            foreach (var logFile in logFiles)
            {
                try
                {
                    var fileName = Path.GetFileNameWithoutExtension(logFile);
                    var dateStr = fileName.Replace("log-", "");

                    // 尝试解析日期 (格式: yyyyMMdd)
                    if (DateTime.TryParseExact(dateStr, "yyyyMMdd",
                        CultureInfo.InvariantCulture,
                        DateTimeStyles.None,
                        out var logDate))
                    {
                        if (logDate < cutoffDate)
                        {
                            File.Delete(logFile);
                            deletedCount++;
                            logger.LogInformation("已删除过期日志文件: {LogFile} (日期: {LogDate})",
                                Path.GetFileName(logFile), logDate.ToString("yyyy-MM-dd"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "删除日志文件失败: {LogFile}", logFile);
                }
            }

            if (deletedCount > 0)
            {
                logger.LogInformation("日志清理完成,共删除 {DeletedCount} 个过期日志文件(保留 {RetentionDays} 天)",
                    deletedCount, RetentionDays);
            }
            else
            {
                logger.LogDebug("没有需要清理的过期日志文件");
            }

            logger.LogInformation("日志清理任务执行完成");
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "日志清理任务执行出错");
            throw; // 让 Quartz 知道任务失败
        }

        return Task.CompletedTask;
    }
}