package user

import (
	"context"
	"strings"

	logicCommon "github.com/perfect-panel/server/internal/logic/common"
	"github.com/perfect-panel/server/internal/model/log"
	usermodel "github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
	var approvedUserID int64
	err := svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		withdrawal, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
		if err != nil {
			if err.Error() == "withdrawal status invalid" {
				return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
			}
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
		}

		// Lock user row and verify sufficient balance before deducting.
		var u usermodel.User
		if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
			Where("id = ?", withdrawal.UserId).First(&u).Error; err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load user failed: %v", err)
		}
		if u.Commission < withdrawal.Amount {
			return errors.Wrapf(xerr.NewErrCode(xerr.UserCommissionNotEnough), "user %d has insufficient commission balance", withdrawal.UserId)
		}

		if err := tx.Model(&usermodel.Withdrawal{}).
			Where("id = ? AND status = 0", withdrawalID).
			Updates(map[string]interface{}{
				"status": 1,
				"reason": "",
			}).Error; err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "approve withdrawal failed: %v", err)
		}

		// Deduct commission atomically inside the transaction.
		if err := tx.Model(&usermodel.User{}).
			Where("id = ?", withdrawal.UserId).
			UpdateColumn("commission", gorm.Expr("commission - ?", withdrawal.Amount)).Error; err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "deduct commission failed: %v", err)
		}

		if err := logicCommon.WriteCommissionLog(tx, withdrawal.UserId, log.CommissionTypeWithdraw, withdrawal.Amount, ""); err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "write commission log failed: %v", err)
		}

		approvedUserID = withdrawal.UserId
		return nil
	})

	if err == nil && approvedUserID > 0 {
		_ = svcCtx.UserModel.ClearUserCache(ctx, &usermodel.User{Id: approvedUserID})
	}
	return err
}

func rejectWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64, reason string) error {
	reason = strings.TrimSpace(reason)
	return svcCtx.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		_, err := logicCommon.LoadPendingWithdrawalForUpdate(ctx, tx, withdrawalID)
		if err != nil {
			if err.Error() == "withdrawal status invalid" {
				return errors.Wrapf(xerr.NewErrCode(xerr.WithdrawalStatusInvalid), "withdrawal %d already processed", withdrawalID)
			}
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "load withdrawal failed: %v", err)
		}

		// Commission was NOT deducted at application time under the new logic,
		// so rejection requires no refund — only a status update.
		return tx.Model(&usermodel.Withdrawal{}).
			Where("id = ? AND status = 0", withdrawalID).
			Updates(map[string]interface{}{
				"status": 2,
				"reason": reason,
			}).Error
	})
}

func isWithdrawalScene(remark string) bool {
	normalized := strings.ToLower(strings.TrimSpace(remark))
	return strings.Contains(normalized, "withdraw") || strings.Contains(normalized, "提现")
}

func logWithdrawalGuard(l logger.Logger, userID int64) {
	l.Errorw("blocked commission overwrite in withdrawal scene", logger.Field("user_id", userID))
}
