package mysql

import (
	"context"
	"database/sql"
	"hyapp/pkg/appcode"
	"hyapp/services/wallet-service/internal/domain/ledger"
	"strings"
)

func (r *Repository) upsertUserGiftWall(ctx context.Context, tx *sql.Tx, metadata giftMetadata, nowMs int64) error {
	if metadata.RobotGift {

		return nil
	}
	chargeAssetType := ledger.NormalizeGiftChargeAssetType(metadata.ChargeAssetType)
	chargeAmount := metadata.ChargeAmount
	if chargeAmount == 0 {

		chargeAmount = metadata.CoinSpent
	}
	totalCoinValue, totalDiamondValue := chargeAmount, int64(0)
	resourceSnapshotJSON := strings.TrimSpace(metadata.ResourceSnapshot)
	if resourceSnapshotJSON == "" {
		resourceSnapshotJSON = "{}"
	}
	presentationJSON := strings.TrimSpace(metadata.PresentationJSON)
	if presentationJSON == "" {
		presentationJSON = "{}"
	}
	giftTypeCode := strings.TrimSpace(metadata.GiftTypeCode)
	if giftTypeCode == "" {
		giftTypeCode = "normal"
	}

	_, err := tx.ExecContext(ctx, `
		INSERT INTO user_gift_wall (
			app_code, user_id, gift_id, gift_name, resource_id, resource_snapshot_json,
			gift_type_code, presentation_json, gift_count, total_value, total_coin_value,
			total_diamond_value, total_gift_point, total_heat_value, charge_asset_type,
			last_price_version, first_received_at_ms, last_received_at_ms, sort_order,
			created_at_ms, updated_at_ms
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON DUPLICATE KEY UPDATE
			gift_name = VALUES(gift_name),
			resource_id = VALUES(resource_id),
			resource_snapshot_json = VALUES(resource_snapshot_json),
			gift_type_code = VALUES(gift_type_code),
			presentation_json = VALUES(presentation_json),
			gift_count = gift_count + VALUES(gift_count),
			total_value = total_value + VALUES(total_value),
			total_coin_value = total_coin_value + VALUES(total_coin_value),
			total_diamond_value = total_diamond_value + VALUES(total_diamond_value),
			total_gift_point = total_gift_point + VALUES(total_gift_point),
			total_heat_value = total_heat_value + VALUES(total_heat_value),
			charge_asset_type = IF(charge_asset_type = VALUES(charge_asset_type), charge_asset_type, ?),
			last_price_version = VALUES(last_price_version),
			last_received_at_ms = VALUES(last_received_at_ms),
			sort_order = VALUES(sort_order),
			updated_at_ms = VALUES(updated_at_ms)
	`,
		appcode.FromContext(ctx),
		metadata.TargetUserID,
		metadata.GiftID,
		metadata.GiftName,
		metadata.ResourceID,
		resourceSnapshotJSON,
		giftTypeCode,
		presentationJSON,
		int64(metadata.GiftCount),
		chargeAmount,
		totalCoinValue,
		totalDiamondValue,
		0,
		metadata.HeatValue,
		chargeAssetType,
		metadata.PriceVersion,
		nowMs,
		nowMs,
		metadata.SortOrder,
		nowMs,
		nowMs,
		giftWallChargeAssetMixed,
	)
	return err
}
