package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"
)

type GetOperationRecordListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetOperationRecordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOperationRecordListLogic {
	return &GetOperationRecordListLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *GetOperationRecordListLogic) GetOperationRecordList(in *system.OperationRecordListReq) (*system.OperationRecordListResp, error) {
	var list []sysModel.SundynixOperationRecord
	var total int64
	db := l.svcCtx.DB.Model(&sysModel.SundynixOperationRecord{})
	if in.Method != "" {
		db = db.Where("method = ?", in.Method)
	}
	if in.Path != "" {
		db = db.Where("path LIKE ?", "%"+in.Path+"%")
	}
	if in.Status > 0 {
		db = db.Where("status = ?", in.Status)
	}
	db.Count(&total)
	current, pageSize := int(in.Current), int(in.PageSize)
	if current <= 0 {
		current = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	if err := db.Offset((current - 1) * pageSize).Limit(pageSize).Order("created_at DESC").Find(&list).Error; err != nil {
		return nil, fmt.Errorf("查询操作日志失败")
	}
	var items []*system.OperationRecordInfo
	for _, r := range list {
		items = append(items, &system.OperationRecordInfo{
			Id:           r.ID,
			ClientId:     r.ClientID,
			Ip:           r.IP,
			Method:       r.Method,
			Path:         r.Path,
			Status:       int32(r.Status),
			Latency:      int64(r.Latency),
			Agent:        r.Agent,
			ErrorMessage: r.ErrorMessage,
			Body:         r.Body,
			Resp:         r.Resp,
			UserId:       r.UserID,
			CreatedAt:    r.CreatedAt.Unix(),
		})
	}

	return &system.OperationRecordListResp{List: items, Total: total}, nil
}
