// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
//
// SPDX-License-Identifier: LicenseRef-MutuaL-1.2

package mcp

import (
	"context"
	"fmt"
	"strings"

	sdk "github.com/modelcontextprotocol/go-sdk/mcp"
)

func (s *Server) callDraftSaveRecipeTool(
	ctx context.Context,
	arguments SaveRecipeArguments,
) (*sdk.CallToolResult, SaveRecipeOutput, error) {
	draftID := strings.TrimSpace(arguments.DraftID)
	if draftID == "" {
		return nil, SaveRecipeOutput{}, fmt.Errorf("draft_id is required when source is draft")
	}

	markdown := arguments.Markdown
	portions := arguments.Portions
	hasMarkdown := strings.TrimSpace(markdown) != ""
	hasPortions := portions >= 1
	if hasMarkdown != hasPortions {
		return nil, SaveRecipeOutput{}, fmt.Errorf(
			"markdown and portions must be provided together when source is draft",
		)
	}
	if !hasMarkdown {
		content, err := s.backend.ReadRecipeContent(ctx, draftID)
		if err != nil {
			return nil, SaveRecipeOutput{}, err
		}
		markdown = content.Content
		portions = content.Portions
	}

	recipeID := strings.TrimSpace(arguments.RecipeID)
	if recipeID != "" {
		if err := validateRecipeID(recipeID); err != nil {
			return nil, SaveRecipeOutput{}, err
		}
		if err := s.backend.UpdateRecipeContent(ctx, recipeID, markdown, portions); err != nil {
			return nil, SaveRecipeOutput{}, err
		}

		return newRecipeOverwriteResult(recipeID)
	}

	savedRecipeID, err := s.backend.SaveRecipeDraft(ctx, draftID, markdown, portions)
	if err != nil {
		return nil, SaveRecipeOutput{}, err
	}
	if strings.TrimSpace(savedRecipeID) == "" {
		return nil, SaveRecipeOutput{}, fmt.Errorf("save recipe draft response missing recipe ID")
	}

	return newRecipeSaveResult(savedRecipeID)
}
