package admin

import (
    "context"
	v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
	admin "github.com/go-nunu/nunu-layout-advanced/api/v1/admin"
	"github.com/go-nunu/nunu-layout-advanced/internal/model"
	"github.com/go-nunu/nunu-layout-advanced/internal/repository"
	"math"
	"strings"
)

type LogRepository interface {
	GetLog(ctx context.Context, id int64) (*model.Log, error)
	GetLogList(ctx context.Context, req admin.SearchLogParams) (*v1.PaginatedResponse[model.Log], error)
}

func NewLogRepository(
	repository *repository.Repository,
) LogRepository {
	return &logRepository{
		Repository: repository,
	}
}

type logRepository struct {
	*repository.Repository
}

func (r *logRepository) GetLog(ctx context.Context, id int64) (*model.Log, error) {
	var res model.Log
	return &res, r.DBWithName(ctx,"admin").Where("id = ?", id).First(&res).Error
}

func (r *logRepository) GetLogList(ctx context.Context, req admin.SearchLogParams) (*v1.PaginatedResponse[model.Log], error) {
	var res []model.Log
	var total int64

	query := r.DBWithName(ctx,"admin").Model(&model.Log{})
	if  req.RequestIp != "" {
		trimmedName := strings.TrimSpace(req.RequestIp)
		// 使用 LIKE 进行模糊匹配
		query = query.Where("request_ip LIKE CONCAT('%', ?, '%')", trimmedName)
	}


	if req.Uid != 0 {
		query = query.Where("uid = ?", req.Uid)
	}

	if req.Api != "" {
		trimmedName := strings.TrimSpace(req.Api)
		// 使用 LIKE 进行模糊匹配
		query = query.Where("api LIKE CONCAT('%', ?, '%')", trimmedName)
	}

	if req.Message != "" {
		trimmedName := strings.TrimSpace(req.Message)
		// 使用 LIKE 进行模糊匹配
		query = query.Where("message LIKE CONCAT('%', ?, '%')", trimmedName)
	}


	if req.ExtraData != "" {
		trimmedName := strings.TrimSpace(req.ExtraData)
		// 使用 LIKE 进行模糊匹配
		query = query.Where("extra_data LIKE CONCAT('%', ?, '%')", trimmedName)
	}

	if req.Column != "" {
		query = query.Order(req.Column + " " + req.Order)
	}

	if err := query.Count(&total).Error; err != nil {
		// 如果连计数都失败了，直接返回错误
		return nil, err
	}


	page := req.Current
	pageSize := req.PageSize

	if page <= 0 {
		page = 1
	}

	if pageSize <= 0 {
		pageSize = 10 // 默认每页 10 条
	} else if pageSize > 100 {
		pageSize = 100 // 每页最多 100 条
	}

	// 计算 offset (偏移量)
	// 例如，第 1 页，offset = (1-1)*10 = 0 (从第0条开始)
	// 第 2 页，offset = (2-1)*10 = 10 (从第10条开始)
	offset := (page - 1) * pageSize
	// 3. 执行最终的查询
	// 在所有条件都添加完毕后，再执行 .Find()
	result := query.Offset(offset).Limit(pageSize).Find(&res)
	if result.Error != nil {
		// 这里的错误可能是数据库连接问题等，而不是“未找到记录”
		return nil, result.Error
	}
	return &v1.PaginatedResponse[model.Log]{
		Records: res,
		Page: page,
		PageSize: pageSize,
		Total: total,
		TotalPages: int(math.Ceil(float64(total) / float64(pageSize))),

	}, nil
}
