package postgres

import (
	"context"
	"crypto/rand"
	"database/sql"
	"encoding/hex"
)

// TicketStore manages WS auth tickets in Postgres.
// v0.32.0: replaces in-memory sync.Map for cross-pod validation.
type TicketStore struct{}

func NewTicketStore() *TicketStore { return &TicketStore{} }

func (s *TicketStore) Issue(ctx context.Context, userID string) (string, error) {
	b := make([]byte, 16)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	id := hex.EncodeToString(b)
	_, err := DB.ExecContext(ctx, `
		INSERT INTO ws_tickets (id, user_id, expires_at)
		VALUES ($1, $2, NOW() + INTERVAL '30 seconds')`, id, userID)
	if err != nil {
		return "", err
	}
	return id, nil
}

func (s *TicketStore) Validate(ctx context.Context, ticketID string) (string, bool) {
	var userID string
	err := DB.QueryRowContext(ctx, `
		DELETE FROM ws_tickets
		WHERE id = $1 AND expires_at > NOW()
		RETURNING user_id`, ticketID).Scan(&userID)
	if err != nil {
		if err == sql.ErrNoRows {
			return "", false
		}
		return "", false
	}
	return userID, true
}

func (s *TicketStore) Reap(ctx context.Context) (int, error) {
	res, err := DB.ExecContext(ctx, `DELETE FROM ws_tickets WHERE expires_at <= NOW()`)
	if err != nil {
		return 0, err
	}
	n, _ := res.RowsAffected()
	return int(n), nil
}
