// SPDX-License-Identifier: GPL-3.0-or-later

// Package cli provides the pay command as a simplified alias for account pay.
package cli

import (
	"fmt"

	"github.com/spf13/cobra"
)

// PayOptions contains options for the pay command.
type PayOptions struct {
	Credits float64
}

// newPayCommand creates the pay command (simplified alias for account pay).
func (c *CLI) newPayCommand() *cobra.Command {
	opts := &PayOptions{}

	cmd := &cobra.Command{
		Use:   "pay",
		Short: "Add credits to your account",
		Long: `Create a payment to add credits to your account.

This generates a Monero payment address with a locked exchange rate
that's valid for 30 minutes.

Credits are used for:
  • Storage: 1 credit/TB/month ($9.99)
  • Retrieval: free (up to 2× storage/month)`,
		Example: `  # Add 5 credits ($74.95)
  privatebackup pay --credits 5

  # Add 2 credits ($29.98)
  privatebackup pay --credits 2`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return c.runPay(opts)
		},
	}

	flags := cmd.Flags()
	flags.Float64Var(&opts.Credits, "credits", 0, "Number of credits to purchase (required)")

	_ = cmd.MarkFlagRequired("credits")

	return cmd
}

// runPay creates a payment intent (delegates to account pay logic).
func (c *CLI) runPay(opts *PayOptions) error {
	if opts.Credits <= 0 {
		return fmt.Errorf("credits must be greater than 0")
	}

	// Check backend connection
	if err := c.checkBackendConnection(); err != nil {
		if IsBackendNotRunning(err) {
			c.renderer.Error("Cannot connect to backend daemon")
			c.renderer.Info("Start it with: privatebackup daemon start")
			return err
		}
		return fmt.Errorf("backend error: %w", err)
	}

	c.renderer.Heading("Payment")
	c.renderer.Newline()

	// In reality, we'd call the backend to create a payment intent
	// and get the XMR amount, rate, and address

	price := opts.Credits * 9.99
	xmrRate := 150.05 // Mock rate - would come from backend
	xmrAmount := price / xmrRate

	c.renderer.KeyValue("Credits", fmt.Sprintf("%.1f", opts.Credits))
	c.renderer.KeyValue("Price", fmt.Sprintf("$%.2f USD", price))
	c.renderer.KeyValue("Rate", fmt.Sprintf("$9.99/credit"))
	c.renderer.Newline()

	c.renderer.Section("Payment Details")
	c.renderer.KeyValue("Amount", fmt.Sprintf("%.4f XMR", xmrAmount))
	c.renderer.KeyValue("XMR Rate", fmt.Sprintf("$%.2f/XMR (locked for 30 min)", xmrRate))
	c.renderer.Newline()

	c.renderer.Info("Send payment to:")
	c.renderer.Printf("  (Monero address would be shown here)\n")
	c.renderer.Newline()

	// In reality, show QR code if terminal supports it
	c.renderer.Info("Waiting for payment confirmation...")
	c.renderer.Info("(Press Ctrl+C to cancel)")

	return nil
}
