package inbox

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type listOptions struct {
	agent      string
	statuses   string
	createdBy  string
	assignedTo string
	limit      int
}

func newListCmd(root *rootOptions) *cobra.Command {
	opts := &listOptions{}

	cmd := &cobra.Command{
		Use:   "list",
		Short: "List threads with filters",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

			agent := opts.agent
			if agent == "" {
				agent = root.agent
			}

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

			s := store.NewInboxStore(sqlDB)
			threads, err := s.ListThreads(ctx, store.ListInput{
				Agent:      agent,
				Statuses:   parseCSV(opts.statuses),
				CreatedBy:  opts.createdBy,
				AssignedTo: opts.assignedTo,
				Limit:      opts.limit,
			})
			if err != nil {
				return err
			}
			if len(threads) == 0 {
				return protocol.NoMatchingWork("no matching work")
			}

			resp := protocol.Success{
				OK:      true,
				Command: "list",
				Data: map[string]any{
					"threads": threads,
				},
			}

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

			for _, thread := range threads {
				if _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\t%s\n", thread.ThreadID, thread.Status, thread.AssignedTo, thread.Subject); err != nil {
					return err
				}
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.agent, "agent", "", "Assigned agent filter shortcut")
	cmd.Flags().StringVar(&opts.statuses, "status", "", "Comma-separated status filter")
	cmd.Flags().StringVar(&opts.createdBy, "created-by", "", "Created-by filter")
	cmd.Flags().StringVar(&opts.assignedTo, "assigned-to", "", "Assigned-to filter")
	cmd.Flags().IntVar(&opts.limit, "limit", 20, "Maximum number of threads")

	return cmd
}
