package fileservice

import (
	"fmt"
	"go-admin/app/admin/models"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/go-admin-team/go-admin-core/sdk/config"
	"gorm.io/gorm"
)

func ClearLogs(orm *gorm.DB) {
	dir := config.LoggerConfig.Path

	if dir == "" {
		dir = "temp/logs"
	}

	// 检查文件夹是否存在
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		fmt.Printf("Directory %s does not exist, skipping cleanup.\n", dir)
		return
	}

	// 获取当前时间
	now := time.Now()
	expirateDay := 7
	var sysConfig models.SysConfig

	orm.Model(&sysConfig).Where("config_key = ?", "log_expirate_date").First(&sysConfig)

	if sysConfig.ConfigValue != "" {
		day, _ := strconv.Atoi(sysConfig.ConfigValue)

		if day > 0 {
			expirateDay = day
		}
	}

	// 遍历指定文件夹中的所有文件
	err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// 只处理普通文件
		if !info.IsDir() {
			// 获取文件的修改时间
			modTime := info.ModTime()

			// 计算文件修改时间与当前时间的差值
			duration := now.Sub(modTime)

			// 如果文件超过7天，则删除
			if duration > time.Duration(expirateDay)*24*time.Hour {
				fmt.Printf("Deleting file: %s (Last modified: %s)\n", path, modTime)
				err := os.Remove(path)
				if err != nil {
					return err
				}
			}
		}

		return nil
	})

	if err != nil {
		fmt.Printf("Error walking the path %v: %v\n", dir, err)
	}
}
