package db
import (
"context"
"fmt"
)
// EnsureUser upserts a user row by username and returns its id. spec.sr.ht is
// single-owner; this seeds the one row core-go's user-scoped webhook model
// references (user_id FK). Idempotent — the daemon calls it every startup.
func (s *Store) EnsureUser(ctx context.Context, username string) (int, error) {
const q = `
INSERT INTO "user" (created, updated, username, email, user_type)
VALUES (NOW() at time zone 'utc', NOW() at time zone 'utc', $1, '', 'USER')
ON CONFLICT (username) DO UPDATE SET updated = NOW() at time zone 'utc'
RETURNING id`
var id int
if err := s.q.QueryRowContext(ctx, q, username).Scan(&id); err != nil {
return 0, fmt.Errorf("ensure user %q: %w", username, err)
}
return id, nil
}