package store

import (
	"context"
	"fmt"

	"git.warky.dev/wdevs/amcs/internal/generatedmodels"
)

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 model generatedmodels.ModelPublicToolAnnotations
		if err := rows.Scan(&model.ToolName, &model.Notes); err != nil {
			return nil, fmt.Errorf("scan tool annotation: %w", err)
		}
		annotations[model.ToolName.String()] = model.Notes.String()
	}
	return annotations, rows.Err()
}
