package store

import (
	"context"
	"fmt"
)

func (db *DB) UpsertToolAnnotation(ctx context.Context, toolName, notes string) error {
	_, err := db.pool.Exec(ctx, `
		insert into tool_annotations (tool_name, notes)
		values ($1, $2)
		on conflict (tool_name) do update
		  set notes      = excluded.notes,
		      updated_at = now()
	`, toolName, notes)
	if err != nil {
		return fmt.Errorf("upsert tool annotation: %w", err)
	}
	return nil
}

func (db *DB) GetToolAnnotations(ctx context.Context) (map[string]string, error) {
	rows, err := db.pool.Query(ctx, `select tool_name, notes from tool_annotations`)
	if err != nil {
		return nil, fmt.Errorf("get tool annotations: %w", err)
	}
	defer rows.Close()

	annotations := make(map[string]string)
	for rows.Next() {
		var toolName, notes string
		if err := rows.Scan(&toolName, &notes); err != nil {
			return nil, fmt.Errorf("scan tool annotation: %w", err)
		}
		annotations[toolName] = notes
	}
	return annotations, rows.Err()
}
