package common

import (
	"context"
	"time"

	"github.com/perfect-panel/server/internal/model/log"
	usermodel "github.com/perfect-panel/server/internal/model/user"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func WriteCommissionLog(tx *gorm.DB, objectID int64, logType uint16, amount int64, orderNo string) error {
	logInfo := log.Commission{
		Type:      logType,
		Amount:    amount,
		OrderNo:   orderNo,
		Timestamp: time.Now().UnixMilli(),
	}

	content, err := logInfo.Marshal()
	if err != nil {
		return err
	}

	return tx.Model(log.SystemLog{}).Create(&log.SystemLog{
		Type:      log.TypeCommission.Uint8(),
		Date:      time.Now().Format(time.DateOnly),
		ObjectID:  objectID,
		Content:   string(content),
		CreatedAt: time.Now(),
	}).Error
}

func LoadPendingWithdrawalForUpdate(ctx context.Context, tx *gorm.DB, withdrawalID int64) (*usermodel.Withdrawal, error) {
	var withdrawal usermodel.Withdrawal
	if err := tx.WithContext(ctx).
		Clauses(clause.Locking{Strength: "UPDATE"}).
		Where("id = ?", withdrawalID).
		First(&withdrawal).Error; err != nil {
		return nil, err
	}
	if withdrawal.Status != 0 {
		return nil, errors.New("withdrawal status invalid")
	}
	return &withdrawal, nil
}
