package mysql

import (
	"context"
	"database/sql"

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

type walletEntry struct {
	AppCode            string
	TransactionID      string
	UserID             int64
	AssetType          string
	AvailableDelta     int64
	FrozenDelta        int64
	AvailableAfter     int64
	FrozenAfter        int64
	CounterpartyUserID int64
	RoomID             string
	CreatedAtMS        int64
}

func (r *Repository) insertEntry(ctx context.Context, tx *sql.Tx, entry walletEntry) error {
	_, err := tx.ExecContext(ctx,
		`INSERT INTO wallet_entries (
		   app_code, transaction_id, user_id, asset_type, available_delta, frozen_delta,
		   available_after, frozen_after, counterparty_user_id, room_id, created_at_ms
		 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
		normalizedEntryAppCode(ctx, entry.AppCode),
		entry.TransactionID,
		entry.UserID,
		entry.AssetType,
		entry.AvailableDelta,
		entry.FrozenDelta,
		entry.AvailableAfter,
		entry.FrozenAfter,
		entry.CounterpartyUserID,
		entry.RoomID,
		entry.CreatedAtMS,
	)
	return err
}

func (r *Repository) balanceAfterTransaction(ctx context.Context, tx *sql.Tx, transactionID string, userID int64, assetType string) (ledger.AssetBalance, error) {
	row := tx.QueryRowContext(ctx,
		`SELECT app_code, user_id, asset_type, available_after, frozen_after
		 FROM wallet_entries
		 WHERE app_code = ? AND transaction_id = ? AND user_id = ? AND asset_type = ?
		 ORDER BY entry_id DESC LIMIT 1`,
		appcode.FromContext(ctx), transactionID, userID, assetType,
	)
	var balance ledger.AssetBalance
	if err := row.Scan(&balance.AppCode, &balance.UserID, &balance.AssetType, &balance.AvailableAmount, &balance.FrozenAmount); err != nil {
		return ledger.AssetBalance{}, err
	}
	return balance, nil
}
