package logic

import (
	"context"
	"time"

	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *CreateOperationRecordLogic) CreateOperationRecord(in *system.CreateOperationRecordReq) (*system.CommonResp, error) {
	record := sysModel.SundynixOperationRecord{
		ClientID:     in.ClientId,
		IP:           in.Ip,
		Method:       in.Method,
		Path:         in.Path,
		Status:       int(in.Status),
		Latency:      time.Duration(in.Latency),
		Agent:        in.Agent,
		ErrorMessage: in.ErrorMessage,
		Body:         in.Body,
		Resp:         in.Resp,
		UserID:       in.UserId,
	}

	if err := l.svcCtx.DB.Create(&record).Error; err != nil {
		l.Errorf("写入操作日志失败: %v", err)
		// 日志写入失败不影响业务，不返回error
	}

	return &system.CommonResp{Code: 200, Msg: "success"}, nil
}
