package refresh_tokens_repo

import (
	"context"
	"time"

	"github.com/jackc/pgx/v5/pgxpool"
)

type RefreshTokensRepo struct {
	pool *pgxpool.Pool
}

func NewRefreshTokensRepo(pool *pgxpool.Pool) *RefreshTokensRepo {
	return &RefreshTokensRepo{
		pool: pool,
	}
}

func (s *RefreshTokensRepo) AddRefreshToken(
	ctx context.Context,
	userId int,
	expiresAt time.Time,
	jti string,
) error {
	_, err := s.pool.Exec(
		ctx,
		`INSERT INTO refresh_tokens (user_id, expires_at, jti) 
		VALUES ($1, $2, $3)`,
		userId,
		expiresAt,
		jti,
	)
	return err
}

func (s *RefreshTokensRepo) ExistsRefreshToken(
	ctx context.Context,
	userId int,
	jti string,
	now time.Time,
) (bool, error) {
	var exists bool

	err := s.pool.QueryRow(
		ctx,
		`SELECT EXISTS(
			SELECT 1 
			FROM refresh_tokens 
			WHERE user_id = $1 
			  AND jti = $2
			  AND expires_at > $3
		)`,
		userId,
		jti,
		now,
	).Scan(&exists)
	if err != nil {
		return false, err
	}

	return exists, nil
}

func (s *RefreshTokensRepo) DeleteRefreshTokenByJti(
	ctx context.Context,
	jti string,
) error {
	_, err := s.pool.Exec(
		ctx,
		`DELETE FROM refresh_tokens 
		WHERE jti = $1`,
		jti,
	)
	return err
}
