package inbox

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type renewOptions struct {
	agent        string
	threadID     string
	leaseSeconds int
}

func newRenewCmd(root *rootOptions) *cobra.Command {
	opts := &renewOptions{}

	cmd := &cobra.Command{
		Use:   "renew",
		Short: "Extend an existing lease",
		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.RenewLease(ctx, store.RenewInput{
				ThreadID:     opts.threadID,
				Agent:        agent,
				LeaseSeconds: opts.leaseSeconds,
			})
			if err != nil {
				return err
			}

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

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

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

	cmd.Flags().StringVar(&opts.agent, "agent", "", "Lease owner")
	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
}
