package log

import (
	"context"

	modellog "github.com/perfect-panel/server/internal/model/log"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type FilterOrderRefundLogLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFilterOrderRefundLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FilterOrderRefundLogLogic {
	return &FilterOrderRefundLogLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FilterOrderRefundLogLogic) FilterOrderRefundLog(req *types.FilterOrderRefundLogRequest) (resp *types.FilterOrderRefundLogResponse, err error) {
	data, total, err := l.svcCtx.LogModel.FilterSystemLog(l.ctx, &modellog.FilterParams{
		Page:     req.Page,
		Size:     req.Size,
		Data:     req.Date,
		Search:   req.Search,
		Type:     modellog.TypeOrderRefund.Uint8(),
		ObjectID: req.OrderId,
	})
	if err != nil {
		l.Errorw("Query order refund log failed", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "Query order refund log failed")
	}

	var list []types.OrderRefundLog
	for _, item := range data {
		var content modellog.OrderRefund
		if err := content.Unmarshal([]byte(item.Content)); err != nil {
			l.Errorf("unmarshal order refund log content failed: %v", err.Error())
			continue
		}
		if req.UserId > 0 && content.TargetUserId != req.UserId && content.RefererUserId != req.UserId && content.OperatorUserId != req.UserId {
			continue
		}
		list = append(list, types.OrderRefundLog{
			OrderId:                content.OrderId,
			OrderNo:                content.OrderNo,
			OperatorUserId:         content.OperatorUserId,
			OperatorAuthIdentifier: content.OperatorAuthIdentifier,
			TargetUserId:           content.TargetUserId,
			UserSubscribeId:        content.UserSubscribeId,
			RefererUserId:          content.RefererUserId,
			CommissionAmount:       content.CommissionAmount,
			Reason:                 content.Reason,
			OrderStatusBefore:      content.OrderStatusBefore,
			OrderStatusAfter:       content.OrderStatusAfter,
			SubscribeStatusBefore:  content.SubscribeStatusBefore,
			SubscribeStatusAfter:   content.SubscribeStatusAfter,
			SubscribeExpireBefore:  content.SubscribeExpireBefore,
			SubscribeExpireAfter:   content.SubscribeExpireAfter,
			CommissionBefore:       content.CommissionBefore,
			CommissionAfter:        content.CommissionAfter,
			Timestamp:              content.Timestamp,
		})
	}
	return &types.FilterOrderRefundLogResponse{
		Total: total,
		List:  list,
	}, nil
}
