package inbox

import (
	"fmt"

	"ai-workflow-skill/internal/protocol"
	"ai-workflow-skill/internal/store"

	"github.com/spf13/cobra"
)

type cancelOptions struct {
	agent     string
	threadID  string
	reason    string
	artifacts artifactOptions
}

func newCancelCmd(root *rootOptions) *cobra.Command {
	opts := &cancelOptions{}

	cmd := &cobra.Command{
		Use:   "cancel",
		Short: "Cancel a thread",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

			agent := opts.agent
			if agent == "" {
				agent = root.agent
			}
			if agent == "" {
				return protocol.InvalidInput("agent is required", nil)
			}
			artifacts, err := resolveArtifacts(opts.artifacts)
			if err != nil {
				return err
			}

			sqlDB, err := openInboxDB(ctx, root.dbPath)
			if err != nil {
				return err
			}
			defer sqlDB.Close()

			s := store.NewInboxStore(sqlDB)
			thread, message, err := s.CancelThread(ctx, store.CancelInput{
				ThreadID:  opts.threadID,
				Agent:     agent,
				Reason:    opts.reason,
				Artifacts: artifacts,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "cancel",
				Data: map[string]any{
					"thread":  thread,
					"message": message,
				},
			}

			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "cancelled thread %s\n", thread.ThreadID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.agent, "agent", "", "Acting agent")
	cmd.Flags().StringVar(&opts.threadID, "thread", "", "Thread ID")
	cmd.Flags().StringVar(&opts.reason, "reason", "", "Cancellation reason")
	addArtifactFlags(cmd, &opts.artifacts)

	_ = cmd.MarkFlagRequired("thread")

	return cmd
}
