package mysql

import (
	"context"
	"database/sql"

	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	"hyapp/services/wallet-service/internal/domain/ledger"
)

// insertPointDiamondGiftIncomeProjection 在送礼账务事务内固化可查询的角色拆分事实。
// POINT_DIAMOND 自营主播会把 Host 与 Agency 两部分合并写入同一个钱包分录；统计不能从该
// 合并 delta 反推角色，因此这里必须原样保存 metadata 的 host_base_amount/agency_amount。
func (r *Repository) insertPointDiamondGiftIncomeProjection(ctx context.Context, tx *sql.Tx, transactionID string, metadata giftMetadata, nowMs int64) error {
	if metadata.HostIncomePolicyType != ledger.HostPolicyTypePointDiamond {
		if metadata.IncomeAssetType == ledger.AssetPointDiamond {
			// POINT_DIAMOND 钱包已准备入账却缺政策类型时不能静默跳过，否则账本与统计事实永久分叉。
			return xerr.New(xerr.Internal, "point diamond gift income policy is invalid")
		}
		return nil
	}
	if metadata.IncomeAssetType != ledger.AssetPointDiamond {
		return xerr.New(xerr.Internal, "point diamond gift income asset is invalid")
	}
	if metadata.HostBaseAmount < 0 || metadata.AgencyAmount < 0 {
		return xerr.New(xerr.Internal, "point diamond gift income amount is invalid")
	}
	if metadata.HostBaseAmount == 0 {
		// 零价礼物不产生收益事实；不写空行可让去重送礼人数只依赖正收益投影。
		return nil
	}
	if tx == nil || metadata.TargetUserID <= 0 {
		return xerr.New(xerr.Internal, "point diamond gift income projection is invalid")
	}
	if metadata.AgencyAmount > 0 && metadata.TargetAgencyOwnerUserID <= 0 {
		return xerr.New(xerr.Internal, "point diamond agency income owner is invalid")
	}

	_, err := tx.ExecContext(ctx, `
		INSERT INTO point_diamond_gift_income_entries (
		  app_code, transaction_id, host_user_id, agency_user_id, sender_user_id,
		  host_base_amount, agency_amount, created_at_ms
		) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
		appcode.FromContext(ctx),
		transactionID,
		metadata.TargetUserID,
		metadata.TargetAgencyOwnerUserID,
		metadata.SenderUserID,
		metadata.HostBaseAmount,
		metadata.AgencyAmount,
		nowMs,
	)
	return err
}
