package knotstream

import (
	"context"
	"database/sql"
	"errors"
	"log/slog"
	"strings"
)

type hostsCursorStore struct {
	db     *sql.DB
	logger *slog.Logger
}

func (s *hostsCursorStore) hostname(key string) string {
	return strings.TrimPrefix(key, "knot:")
}

func (s *hostsCursorStore) Set(key string, cursor string) {
	host := s.hostname(key)
	if _, err := s.db.ExecContext(context.Background(),
		`update hosts set last_tid = $1 where hostname = $2 and $1 > last_tid`,
		cursor, host,
	); err != nil {
		s.logger.Error("hosts cursor set failed", "host", host, "cursor", cursor, "err", err)
	}
}

func (s *hostsCursorStore) Get(key string) string {
	host := s.hostname(key)
	var tid string
	err := s.db.QueryRowContext(context.Background(),
		`select last_tid from hosts where hostname = $1`,
		host,
	).Scan(&tid)
	if err != nil {
		if !errors.Is(err, sql.ErrNoRows) {
			s.logger.Error("hosts cursor get failed", "host", host, "err", err)
		}
		return ""
	}
	return tid
}
