package db

import (
	"context"
	"errors"
	"fmt"
	"time"

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

type PairTokenRow struct {
	ID          string
	TokenHash   string
	Description string
	CreatedBy   int64
	CreatedAt   time.Time
	ExpiresAt   time.Time
	UsedAt      *time.Time
	UsedByAgent string
}

var ErrPairTokenNotFound = errors.New("pairing token not found or already used")

func (db *DB) CreatePairToken(ctx context.Context, r PairTokenRow) error {
	_, err := db.pool.Exec(ctx, `
		INSERT INTO pair_tokens (id, token_hash, description, created_by, expires_at)
		VALUES ($1, $2, $3, $4, $5)
	`, r.ID, r.TokenHash, r.Description, r.CreatedBy, r.ExpiresAt)
	if err != nil {
		return fmt.Errorf("insert pair_token: %w", err)
	}
	return nil
}

// ConsumePairToken looks up a token by its hash, validates that it's
// unused + unexpired, and atomically marks it consumed. Returns the row
// on success. Returns ErrPairTokenNotFound if no such valid token.
func (db *DB) ConsumePairToken(ctx context.Context, hash, agentID, fingerprint string) (*PairTokenRow, error) {
	var r PairTokenRow
	err := db.pool.QueryRow(ctx, `
		UPDATE pair_tokens
		SET used_at = NOW(), used_by_agent = $2, issued_cert_fingerprint = $3
		WHERE token_hash = $1
		  AND used_at IS NULL
		  AND expires_at > NOW()
		RETURNING id, token_hash, description, created_by, created_at, expires_at
	`, hash, agentID, fingerprint).Scan(
		&r.ID, &r.TokenHash, &r.Description, &r.CreatedBy, &r.CreatedAt, &r.ExpiresAt,
	)
	if errors.Is(err, pgx.ErrNoRows) {
		return nil, ErrPairTokenNotFound
	}
	if err != nil {
		return nil, fmt.Errorf("consume pair_token: %w", err)
	}
	return &r, nil
}

func (db *DB) ListPairTokens(ctx context.Context) ([]PairTokenRow, error) {
	rows, err := db.pool.Query(ctx, `
		SELECT id, token_hash, description, created_by, created_at, expires_at, used_at, COALESCE(used_by_agent, '')
		FROM pair_tokens
		ORDER BY created_at DESC
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []PairTokenRow
	for rows.Next() {
		var r PairTokenRow
		if err := rows.Scan(&r.ID, &r.TokenHash, &r.Description, &r.CreatedBy, &r.CreatedAt, &r.ExpiresAt, &r.UsedAt, &r.UsedByAgent); err != nil {
			return nil, err
		}
		out = append(out, r)
	}
	return out, rows.Err()
}
