package keybase

import (
	"context"
	"fmt"
)

func (am *ActionManager) GetSessionByID(ctx context.Context, sessionID string) (*SessionResult, error) {
	am.kb.mu.RLock()
	defer am.kb.mu.RUnlock()

	sess, err := am.kb.queries.GetSessionByID(ctx, sessionID)
	if err != nil {
		return nil, fmt.Errorf("get session: %w", err)
	}

	return sessionToResult(&sess), nil
}

func (am *ActionManager) GetCurrentSession(ctx context.Context) (*SessionResult, error) {
	am.kb.mu.RLock()
	defer am.kb.mu.RUnlock()

	if am.kb.didID == 0 {
		return nil, fmt.Errorf("DID not initialized")
	}

	sess, err := am.kb.queries.GetCurrentSession(ctx, am.kb.didID)
	if err != nil {
		return nil, fmt.Errorf("get current session: %w", err)
	}

	return sessionToResult(&sess), nil
}

func (am *ActionManager) UpdateSessionActivity(ctx context.Context, sessionID string) error {
	am.kb.mu.Lock()
	defer am.kb.mu.Unlock()

	sess, err := am.kb.queries.GetSessionByID(ctx, sessionID)
	if err != nil {
		return fmt.Errorf("get session: %w", err)
	}

	return am.kb.queries.UpdateSessionActivity(ctx, sess.ID)
}

func (am *ActionManager) SetCurrentSession(ctx context.Context, sessionID string) error {
	am.kb.mu.Lock()
	defer am.kb.mu.Unlock()

	if am.kb.didID == 0 {
		return fmt.Errorf("DID not initialized")
	}

	sess, err := am.kb.queries.GetSessionByID(ctx, sessionID)
	if err != nil {
		return fmt.Errorf("get session: %w", err)
	}

	return am.kb.queries.SetCurrentSession(ctx, SetCurrentSessionParams{
		ID:    sess.ID,
		DidID: am.kb.didID,
	})
}

func (am *ActionManager) DeleteExpiredSessions(ctx context.Context) error {
	am.kb.mu.Lock()
	defer am.kb.mu.Unlock()

	return am.kb.queries.DeleteExpiredSessions(ctx)
}

func sessionToResult(sess *Session) *SessionResult {
	return &SessionResult{
		ID:           sess.ID,
		SessionID:    sess.SessionID,
		DeviceInfo:   sess.DeviceInfo,
		IsCurrent:    sess.IsCurrent == 1,
		LastActivity: sess.LastActivity,
		ExpiresAt:    sess.ExpiresAt,
		CreatedAt:    sess.CreatedAt,
	}
}
