package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"git.warky.dev/wdevs/whatshooked/pkg/config"
	"github.com/spf13/cobra"
)

// hooksCmd is the parent command for hook management
var hooksCmd = &cobra.Command{
	Use:   "hooks",
	Short: "Manage webhooks",
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		listHooks(client)
	},
}

var hooksListCmd = &cobra.Command{
	Use:   "list",
	Short: "List all hooks",
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		listHooks(client)
	},
}

var hooksAddCmd = &cobra.Command{
	Use:   "add",
	Short: "Add a new hook",
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		addHook(client)
	},
}

var hooksRemoveCmd = &cobra.Command{
	Use:   "remove <hook_id>",
	Short: "Remove a hook",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		removeHook(client, args[0])
	},
}

func init() {
	hooksCmd.AddCommand(hooksListCmd)
	hooksCmd.AddCommand(hooksAddCmd)
	hooksCmd.AddCommand(hooksRemoveCmd)
}

func listHooks(client *Client) {
	resp, err := client.Get("/api/hooks")
	checkError(err)
	defer resp.Body.Close()

	var hooks []config.Hook
	checkError(decodeJSON(resp, &hooks))

	if len(hooks) == 0 {
		fmt.Println("No hooks configured")
		return
	}

	fmt.Printf("Configured hooks (%d):\n\n", len(hooks))
	for _, hook := range hooks {
		status := "inactive"
		if hook.Active {
			status = "active"
		}
		fmt.Printf("ID:          %s\n", hook.ID)
		fmt.Printf("Name:        %s\n", hook.Name)
		fmt.Printf("URL:         %s\n", hook.URL)
		fmt.Printf("Method:      %s\n", hook.Method)
		fmt.Printf("Status:      %s\n", status)
		if len(hook.Events) > 0 {
			fmt.Printf("Events:      %v\n", hook.Events)
		} else {
			fmt.Printf("Events:      all (no filter)\n")
		}
		if hook.Description != "" {
			fmt.Printf("Description: %s\n", hook.Description)
		}
		fmt.Println()
	}
}

func addHook(client *Client) {
	var hook config.Hook
	scanner := bufio.NewScanner(os.Stdin)

	fmt.Print("Hook ID: ")
	if _, err := fmt.Scanln(&hook.ID); err != nil {
		checkError(fmt.Errorf("error reading hook ID: %v", err))
	}

	fmt.Print("Hook Name: ")
	if _, err := fmt.Scanln(&hook.Name); err != nil {
		checkError(fmt.Errorf("error reading hook name: %v", err))
	}

	fmt.Print("Webhook URL: ")
	if _, err := fmt.Scanln(&hook.URL); err != nil {
		checkError(fmt.Errorf("error reading webhook URL: %v", err))
	}

	fmt.Print("HTTP Method (POST): ")
	if _, err := fmt.Scanln(&hook.Method); err == nil {
		// Successfully read input
		fmt.Printf("Selected Method %s", hook.Method)
	}
	if hook.Method == "" {
		hook.Method = "POST"
	}

	// Prompt for events with helpful examples
	fmt.Println("\nAvailable events:")
	fmt.Println("  WhatsApp: whatsapp.connected, whatsapp.disconnected, whatsapp.qr.code")
	fmt.Println("  Messages: message.received, message.sent, message.delivered, message.read")
	fmt.Println("  Hooks:    hook.triggered, hook.success, hook.failed")
	fmt.Print("\nEvents (comma-separated, or press Enter for all): ")

	scanner.Scan()
	eventsInput := strings.TrimSpace(scanner.Text())

	if eventsInput != "" {
		// Split by comma and trim whitespace
		eventsList := strings.Split(eventsInput, ",")
		hook.Events = make([]string, 0, len(eventsList))
		for _, event := range eventsList {
			trimmed := strings.TrimSpace(event)
			if trimmed != "" {
				hook.Events = append(hook.Events, trimmed)
			}
		}
	}

	fmt.Print("\nDescription (optional): ")
	scanner.Scan()
	hook.Description = strings.TrimSpace(scanner.Text())

	hook.Active = true

	resp, err := client.Post("/api/hooks/add", hook)
	checkError(err)
	defer resp.Body.Close()

	fmt.Println("Hook added successfully")
}

func removeHook(client *Client, id string) {
	req := map[string]string{"id": id}

	resp, err := client.Post("/api/hooks/remove", req)
	checkError(err)
	defer resp.Body.Close()

	fmt.Println("Hook removed successfully")
}
