package notes

import (
	"context"
	_ "embed"
	"encoding/json/v2"

	"example.com/sonny-notes/gen/mcp"
	"example.com/sonny-notes/gen/pkg/mcpx"
	"example.com/sonny-notes/gen/types"
)

//go:embed approved-notes.json
var fixture []byte

type Server struct {
	mcp.UnimplementedMCPServer
	approved map[string]types.NoteLookupResult
}

func New() (*Server, error) {
	s := &Server{}
	if err := json.Unmarshal(fixture, &s.approved); err != nil {
		return nil, err
	}
	return s, nil
}

func (s *Server) Note_lookup(ctx context.Context, p *types.NoteLookupParams) (*types.NoteLookupResult, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	if p == nil || p.Valid() != nil {
		return nil, &mcpx.ToolError{Code: "invalid_argument", Message: "collection and id must be valid identifiers"}
	}
	// The launching host grants only this embedded collection. A tool argument
	// selects a note within that grant; it cannot expand the grant.
	if p.Collection != "approved" {
		return nil, &mcpx.ToolError{Code: "permission_denied", Message: "collection is not permitted"}
	}
	note, ok := s.approved[p.ID]
	if !ok {
		return nil, &mcpx.ToolError{Code: "not_found", Message: "note was not found"}
	}
	return &note, nil
}
