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"
)

func approveWithdrawal(ctx context.Context, svcCtx *svc.ServiceContext, withdrawalID int64) error {
	return 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)
		}

		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)
		}

		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)
		}
		return nil
	})
}

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 {
		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)
		}

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

		if err := svcCtx.UserModel.UpdateCommission(ctx, withdrawal.UserId, withdrawal.Amount, tx); err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "refund commission failed: %v", err)
		}

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

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))
}
