package wallet

import (
	"strings"
	"sync"
	"time"
)

const walletConnectSessionTTL = 24 * time.Hour

type storedWalletConnectSession struct {
	SessionID string
	Address   string
	ChainID   int
	Connected bool
	Status    string
	Message   string
	UpdatedAt time.Time
}

var (
	walletConnectSessionMu sync.RWMutex
	walletConnectSessions  = map[string]storedWalletConnectSession{}
)

func purgeExpiredWalletConnectSessions(now time.Time) {
	for id, session := range walletConnectSessions {
		if now.Sub(session.UpdatedAt) > walletConnectSessionTTL {
			delete(walletConnectSessions, id)
		}
	}
}

// RegisterClientSession records a browser-paired WalletConnect session snapshot.
func RegisterClientSession(sessionID, address string, chainID int) *Session {
	sessionID = strings.TrimSpace(sessionID)
	address = strings.TrimSpace(address)
	now := time.Now().UTC()

	walletConnectSessionMu.Lock()
	defer walletConnectSessionMu.Unlock()
	purgeExpiredWalletConnectSessions(now)

	record := storedWalletConnectSession{
		SessionID: sessionID,
		Address:   address,
		ChainID:   chainID,
		Connected: true,
		Status:    WalletConnectStatusClient,
		Message:   "WalletConnect session registered by browser client after pairing.",
		UpdatedAt: now,
	}
	walletConnectSessions[sessionID] = record
	return sessionFromStored(record)
}

func lookupWalletConnectSession(sessionID string) (*Session, bool) {
	sessionID = strings.TrimSpace(sessionID)
	if sessionID == "" {
		return nil, false
	}

	now := time.Now().UTC()
	walletConnectSessionMu.Lock()
	defer walletConnectSessionMu.Unlock()
	purgeExpiredWalletConnectSessions(now)

	record, ok := walletConnectSessions[sessionID]
	if !ok {
		return nil, false
	}
	if now.Sub(record.UpdatedAt) > walletConnectSessionTTL {
		delete(walletConnectSessions, sessionID)
		return nil, false
	}
	return sessionFromStored(record), true
}

func sessionFromStored(record storedWalletConnectSession) *Session {
	return &Session{
		SessionID: record.SessionID,
		Address:   record.Address,
		ChainID:   record.ChainID,
		Connected: record.Connected,
		Status:    record.Status,
		Message:   record.Message,
	}
}
