package order

import (
	"context"
	"encoding/json"
	"math"
	"time"

	"github.com/google/uuid"

	commonLogic "github.com/perfect-panel/server/internal/logic/common"
	"github.com/perfect-panel/server/internal/model/log"
	"github.com/perfect-panel/server/pkg/constant"

	"gorm.io/gorm"

	"github.com/hibiken/asynq"
	"github.com/perfect-panel/server/internal/model/order"
	"github.com/perfect-panel/server/internal/model/user"
	"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/tool"
	"github.com/perfect-panel/server/pkg/xerr"
	queue "github.com/perfect-panel/server/queue/types"
	"github.com/pkg/errors"
)

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

// NewRenewalLogic creates a new renewal logic instance for subscription renewal operations
func NewRenewalLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RenewalLogic {
	return &RenewalLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RenewalLogic) resolveRenewalTargetSubscribe(requested *user.SubscribeDetails, entitlement *commonLogic.EntitlementContext, currentUserID int64) (*user.SubscribeDetails, error) {
	if requested == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "requested user subscribe is empty")
	}

	effectiveUserID := currentUserID
	if entitlement != nil && entitlement.EffectiveUserID > 0 {
		effectiveUserID = entitlement.EffectiveUserID
	}

	if effectiveUserID == currentUserID {
		if requested.UserId != currentUserID {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "user subscribe does not belong to current user")
		}
		return requested, nil
	}

	if requested.UserId != currentUserID && requested.UserId != effectiveUserID {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "user subscribe does not belong to current family entitlement")
	}
	if requested.UserId == effectiveUserID {
		return requested, nil
	}

	ownerSubscribe, err := l.findOwnerRenewalSubscribe(effectiveUserID, requested.SubscribeId)
	if err != nil {
		return nil, err
	}
	commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "renewal_target_resolved",
		"[SubscriptionFlow] renewal target redirected to family owner subscription",
		logger.Field("user_id", currentUserID),
		logger.Field("effective_user_id", effectiveUserID),
		logger.Field("requested_user_subscribe_id", requested.Id),
		logger.Field("requested_subscribe_owner_user_id", requested.UserId),
		logger.Field("resolved_user_subscribe_id", ownerSubscribe.Id),
		logger.Field("resolved_subscribe_owner_user_id", ownerSubscribe.UserId),
		logger.Field("subscribe_id", requested.SubscribeId),
	)
	return ownerSubscribe, nil
}

func (l *RenewalLogic) findOwnerRenewalSubscribe(ownerUserID, subscribeID int64) (*user.SubscribeDetails, error) {
	var target user.SubscribeDetails
	err := l.svcCtx.DB.WithContext(l.ctx).
		Model(&user.Subscribe{}).
		Preload("Subscribe").
		Where("user_id = ? AND subscribe_id = ? AND token != ''", ownerUserID, subscribeID).
		Where("status IN ?", []int64{0, 1, 2, 3}).
		Order("expire_time DESC").
		Order("updated_at DESC").
		Order("id DESC").
		First(&target).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "owner subscribe not found for renewal")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find owner subscribe error: %v", err.Error())
	}
	return &target, nil
}

// Renewal processes subscription renewal orders including discount calculation,
// coupon validation, gift amount deduction, fee calculation, and order creation
func (l *RenewalLogic) Renewal(req *types.RenewalOrderRequest) (resp *types.RenewalOrderResponse, err error) {
	u, ok := l.ctx.Value(constant.CtxKeyUser).(*user.User)
	if !ok {
		logger.Error("current user is not found in context")
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidAccess), "Invalid Access")
	}
	// Resolve entitlement: member's subscription goes to owner
	entitlement, entErr := commonLogic.ResolveEntitlementUser(l.ctx, l.svcCtx.DB, u.Id)
	if entErr != nil {
		return nil, entErr
	}

	commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "order_create_start",
		"[SubscriptionFlow] renewal order creation started",
		logger.Field("order_kind", "renewal"),
		logger.Field("user_id", u.Id),
		logger.Field("effective_user_id", entitlement.EffectiveUserID),
		logger.Field("requested_user_subscribe_id", req.UserSubscribeID),
		logger.Field("quantity", req.Quantity),
		logger.Field("payment_id", req.Payment),
		logger.Field("coupon", req.Coupon),
	)
	if req.Quantity <= 0 {
		l.Debugf("[Renewal] Quantity is less than or equal to 0, setting to 1")
		req.Quantity = 1
	}

	// Validate quantity limit
	if req.Quantity > MaxQuantity {
		l.Errorw("[Renewal] Quantity exceeds maximum limit", logger.Field("quantity", req.Quantity), logger.Field("max", MaxQuantity))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "quantity exceeds maximum limit of %d", MaxQuantity)
	}

	orderNo := tool.GenerateTradeNo()
	// find requested user subscribe, then resolve it to the real entitlement owner.
	requestedSubscribe, err := l.svcCtx.UserModel.FindOneUserSubscribe(l.ctx, req.UserSubscribeID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user subscribe error: %v", err.Error())
	}
	userSubscribe, err := l.resolveRenewalTargetSubscribe(requestedSubscribe, entitlement, u.Id)
	if err != nil {
		return nil, err
	}
	// find subscription
	sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, userSubscribe.SubscribeId)
	if err != nil {
		l.Errorw("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("subscribe_id", userSubscribe.SubscribeId))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find subscribe error: %v", err.Error())
	}
	// check subscribe plan status
	if !*sub.Sell {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "subscribe not sell")
	}
	newUserDiscount, err := resolveNewUserDiscountEligibility(l.ctx, l.svcCtx.DB, u.Id, sub.Id, req.Quantity, sub.Discount)
	if err != nil {
		l.Errorw("[Renewal] Database query error resolving new user eligibility",
			logger.Field("error", err.Error()),
			logger.Field("user_id", u.Id),
		)
		return nil, err
	}
	var discount float64 = 1
	if len(newUserDiscount.Discounts) > 0 {
		discount = getDiscount(newUserDiscount.Discounts, req.Quantity, newUserDiscount.EligibleForDiscount)
	}
	price := sub.UnitPrice * req.Quantity
	amount := int64(math.Round(float64(price) * discount))
	discountAmount := price - amount

	// Validate amount to prevent overflow
	if amount > MaxOrderAmount {
		l.Errorw("[Renewal] Order amount exceeds maximum limit",
			logger.Field("amount", amount),
			logger.Field("max", MaxOrderAmount),
			logger.Field("user_id", u.Id),
			logger.Field("subscribe_id", sub.Id))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "order amount exceeds maximum limit")
	}

	var coupon int64 = 0
	if req.Coupon != "" {
		couponInfo, err := l.svcCtx.CouponModel.FindOneByCode(l.ctx, req.Coupon)
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotExist), "coupon not found")
			}
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
		}
		if couponInfo.Count != 0 && couponInfo.Count <= couponInfo.UsedCount {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon used")
		}
		couponSub := tool.StringToInt64Slice(couponInfo.Subscribe)

		if len(couponSub) > 0 && !tool.Contains(couponSub, sub.Id) {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponNotApplicable), "coupon not match")
		}
		var count int64
		err = l.svcCtx.DB.Transaction(func(tx *gorm.DB) error {
			return tx.Model(&order.Order{}).Where("user_id = ? and coupon = ?", u.Id, req.Coupon).Count(&count).Error
		})
		if err != nil {
			l.Errorw("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id), logger.Field("coupon", req.Coupon))
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find coupon error: %v", err.Error())
		}
		if count >= couponInfo.UserLimit {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.CouponInsufficientUsage), "coupon limit exceeded")
		}
		coupon = calculateCoupon(amount, couponInfo)
	}
	payment, err := l.svcCtx.PaymentModel.FindOne(l.ctx, req.Payment)
	if err != nil {
		l.Errorw("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("payment", req.Payment))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find payment error: %v", err.Error())
	}
	amount -= coupon

	var deductionAmount int64
	// Check user deduction amount
	if u.GiftAmount > 0 {
		if u.GiftAmount >= amount {
			deductionAmount = amount
			u.GiftAmount -= deductionAmount
			amount = 0
		} else {
			deductionAmount = u.GiftAmount
			amount -= u.GiftAmount
			u.GiftAmount = 0
		}
	}

	var feeAmount int64
	// Calculate the handling fee
	if amount > 0 {
		feeAmount = calculateFee(amount, payment)
	}

	amount += feeAmount

	// Final validation after adding fee
	if amount > MaxOrderAmount {
		l.Errorw("[Renewal] Final order amount exceeds maximum limit after fee",
			logger.Field("amount", amount),
			logger.Field("max", MaxOrderAmount),
			logger.Field("user_id", u.Id))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.InvalidParams), "order amount exceeds maximum limit")
	}

	isNew, err := l.svcCtx.OrderModel.IsUserEligibleForNewOrder(l.ctx, u.Id)
	if err != nil {
		l.Errorw("[Renewal] Database query error", logger.Field("error", err.Error()), logger.Field("user_id", u.Id))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find user order error: %v", err.Error())
	}

	// create order
	orderInfo := order.Order{
		UserId:             u.Id,
		SubscriptionUserId: entitlement.EffectiveUserID,
		ParentId:           userSubscribe.OrderId,
		OrderNo:            orderNo,
		Type:               2,
		Quantity:           req.Quantity,
		Price:              price,
		Amount:             amount,
		GiftAmount:         deductionAmount,
		Discount:           discountAmount,
		Coupon:             req.Coupon,
		CouponDiscount:     coupon,
		PaymentId:          payment.Id,
		Method:             canonicalOrderMethod(payment.Platform),
		FeeAmount:          feeAmount,
		Status:             1,
		SubscribeId:        userSubscribe.SubscribeId,
		SubscribeToken:     userSubscribe.Token,
		AppAccountToken:    uuid.New().String(),
		IsNew:              isNew,
	}
	// Database transaction
	err = l.svcCtx.DB.Transaction(func(db *gorm.DB) error {
		// update user deduction && Pre deduction ,Return after canceling the order
		if orderInfo.GiftAmount > 0 {
			// update user deduction && Pre deduction ,Return after canceling the order
			if err := l.svcCtx.UserModel.Update(l.ctx, u, db); err != nil {
				l.Errorw("[Renewal] Database update error", logger.Field("error", err.Error()), logger.Field("user", u))
				return err
			}
			// create deduction record
			giftLog := log.Gift{
				Type:        log.GiftTypeReduce,
				OrderNo:     orderInfo.OrderNo,
				SubscribeId: 0,
				Amount:      orderInfo.GiftAmount,
				Balance:     u.GiftAmount,
				Remark:      "Renewal order deduction",
				Timestamp:   time.Now().UnixMilli(),
			}
			content, _ := giftLog.Marshal()

			if err := db.Model(&log.SystemLog{}).Create(&log.SystemLog{
				Type:     log.TypeGift.Uint8(),
				Date:     time.Now().Format(time.DateOnly),
				ObjectID: u.Id,
				Content:  string(content),
			}).Error; err != nil {
				l.Errorw("[Renewal] Database insert error", logger.Field("error", err.Error()), logger.Field("deductionLog", giftLog))
				return err
			}
		}
		// insert order
		return db.Model(&order.Order{}).Create(&orderInfo).Error
	})
	if err != nil {
		l.Errorw("[Renewal] Database insert error", logger.Field("error", err.Error()), logger.Field("order", orderInfo))
		return nil, errors.Wrapf(err, "insert order error: %v", err.Error())
	}

	commonLogic.SubscriptionTraceInfo(l.Logger, commonLogic.SubscriptionTraceFlowOrder, "order_created",
		"[SubscriptionFlow] renewal order persisted",
		append(commonLogic.OrderTraceFields(&orderInfo),
			logger.Field("requested_user_subscribe_id", req.UserSubscribeID),
			logger.Field("requested_subscribe_owner_user_id", requestedSubscribe.UserId),
			logger.Field("resolved_user_subscribe_id", userSubscribe.Id),
			logger.Field("resolved_subscribe_owner_user_id", userSubscribe.UserId),
		)...,
	)
	// Deferred task
	payload := queue.DeferCloseOrderPayload{
		OrderNo: orderInfo.OrderNo,
	}
	val, err := json.Marshal(payload)
	if err != nil {
		l.Errorw("[Renewal] Marshal payload error", logger.Field("error", err.Error()), logger.Field("payload", payload))
	}
	task := asynq.NewTask(queue.DeferCloseOrder, val, asynq.MaxRetry(3))
	taskInfo, err := l.svcCtx.Queue.Enqueue(task, asynq.ProcessIn(CloseOrderTimeMinutes*time.Minute))
	if err != nil {
		l.Errorw("[Renewal] Enqueue task error", logger.Field("error", err.Error()), logger.Field("task", task))
	} else {
		l.Infow("[Renewal] Enqueue task success", logger.Field("TaskID", taskInfo.ID))
	}
	return &types.RenewalOrderResponse{
		OrderNo:         orderInfo.OrderNo,
		AppAccountToken: orderInfo.AppAccountToken,
	}, nil
}
