package postgres

import (
	"time"

	"github.com/jmoiron/sqlx"
	"github.com/ajaxray/geek-life/model"
)

// SessionRepository implements the session repository interface for PostgreSQL
type SessionRepository struct {
	db *sqlx.DB
}

// NewSessionRepository creates a new session repository
func NewSessionRepository(db *sqlx.DB) *SessionRepository {
	return &SessionRepository{db: db}
}

// GetByToken retrieves a session by token
func (r *SessionRepository) GetByToken(token string) (*model.UserSession, error) {
	var session model.UserSession
	query := `SELECT id, user_id, token, expires_at, created_at 
			  FROM user_sessions WHERE token = $1 AND expires_at > NOW()`
	err := r.db.Get(&session, query, token)
	if err != nil {
		return nil, err
	}
	return &session, nil
}

// Create creates a new session
func (r *SessionRepository) Create(userID int64, token string, expiresAt int64) (*model.UserSession, error) {
	session := &model.UserSession{
		UserID:    userID,
		Token:     token,
		ExpiresAt: time.Unix(expiresAt, 0),
		CreatedAt: time.Now(),
	}

	query := `INSERT INTO user_sessions (user_id, token, expires_at, created_at) 
			  VALUES ($1, $2, $3, $4) RETURNING id`
	err := r.db.QueryRow(query, session.UserID, session.Token, session.ExpiresAt, session.CreatedAt).Scan(&session.ID)
	if err != nil {
		return nil, err
	}

	return session, nil
}

// Delete deletes a session
func (r *SessionRepository) Delete(session *model.UserSession) error {
	query := `DELETE FROM user_sessions WHERE id = $1`
	_, err := r.db.Exec(query, session.ID)
	return err
}

// DeleteExpired deletes all expired sessions
func (r *SessionRepository) DeleteExpired() error {
	query := `DELETE FROM user_sessions WHERE expires_at <= NOW()`
	_, err := r.db.Exec(query)
	return err
}