package inbox

import (
	"errors"
	"fmt"

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

	"github.com/spf13/cobra"
)

type claimOptions struct {
	agent        string
	threadID     string
	leaseSeconds int
}

func newClaimCmd(root *rootOptions) *cobra.Command {
	opts := &claimOptions{}

	cmd := &cobra.Command{
		Use:   "claim",
		Short: "Acquire a lease on a pending 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)
			}

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

			s := store.NewInboxStore(sqlDB)
			result, err := s.ClaimThread(ctx, store.ClaimInput{
				ThreadID:     opts.threadID,
				Agent:        agent,
				LeaseSeconds: opts.leaseSeconds,
			})
			if err != nil {
				if errors.Is(err, store.ErrLeaseConflict) {
					return fmt.Errorf("lease conflict: %w", err)
				}
				return err
			}

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

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

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

	cmd.Flags().StringVar(&opts.agent, "agent", "", "Claiming agent")
	cmd.Flags().StringVar(&opts.threadID, "thread", "", "Thread ID")
	cmd.Flags().IntVar(&opts.leaseSeconds, "lease-seconds", 900, "Lease duration in seconds")

	_ = cmd.MarkFlagRequired("thread")

	return cmd
}
