package cli

import (
	"context"
	"fmt"
	"net/url"
	"os"

	"edp.buildth.ing/DevFW-CICD/edge-connect-client/internal/core/domain"
	"github.com/spf13/cobra"
)

// validateBaseURL checks if the provided string is a valid base URL.
// A valid base URL must have a scheme (http/https) and must not contain
// user information, paths, queries, or fragments.
func validateBaseURL(rawURL string) error {
	u, err := url.Parse(rawURL)
	if err != nil {
		return fmt.Errorf("invalid URL format: %w", err)
	}

	if u.Scheme == "" {
		return fmt.Errorf("URL must have a scheme (e.g., http, https)")
	}

	if u.User != nil {
		return fmt.Errorf("URL should not contain user information")
	}

	if u.Path != "" && u.Path != "/" {
		return fmt.Errorf("URL should not contain a path")
	}

	if u.RawQuery != "" {
		return fmt.Errorf("URL should not contain a query string")
	}

	if u.Fragment != "" {
		return fmt.Errorf("URL should not contain a fragment")
	}

	return nil
}
var (
	organization string
	appName      string
	appVersion   string
	region       string
)

var appCmd = &cobra.Command{
	Use:   "app",
	Short: "Manage Edge Connect applications",
	Long:  `Create, show, list, and delete Edge Connect applications.`,
}

var createAppCmd = &cobra.Command{
	Use:   "create",
	Short: "Create a new Edge Connect application",
	Run: func(cmd *cobra.Command, args []string) {
		app := &domain.App{
			Key: domain.AppKey{
				Organization: organization,
				Name:         appName,
				Version:      appVersion,
			},
		}

		err := services.AppService.CreateApp(context.Background(), region, app)
		if err != nil {
			fmt.Printf("Error creating app: %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Application created successfully")
	},
}

var showAppCmd = &cobra.Command{
	Use:   "show",
	Short: "Show details of an Edge Connect application",
	Run: func(cmd *cobra.Command, args []string) {
		appKey := domain.AppKey{
			Organization: organization,
			Name:         appName,
			Version:      appVersion,
		}

		app, err := services.AppService.ShowApp(context.Background(), region, appKey)
		if err != nil {
			// Handle domain-specific errors with appropriate user feedback
			if domain.IsNotFoundError(err) {
				fmt.Printf("Application %s/%s (version %s) not found in region %s\n", 
					appKey.Organization, appKey.Name, appKey.Version, region)
				os.Exit(1)
			}
			if domain.IsValidationError(err) {
				fmt.Printf("Validation error: %v\n", err)
				os.Exit(1)
			}
			fmt.Printf("Error showing app: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Application details:\n%+v\n", app)
	},
}

var listAppsCmd = &cobra.Command{
	Use:   "list",
	Short: "List Edge Connect applications",
	Run: func(cmd *cobra.Command, args []string) {
		appKey := domain.AppKey{
			Organization: organization,
			Name:         appName,
			Version:      appVersion,
		}

		apps, err := services.AppService.ShowApps(context.Background(), region, appKey)
		if err != nil {
			fmt.Printf("Error listing apps: %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Applications:")
		for _, app := range apps {
			fmt.Printf("%+v\n", app)
		}
	},
}

var deleteAppCmd = &cobra.Command{
	Use:   "delete",
	Short: "Delete an Edge Connect application",
	Run: func(cmd *cobra.Command, args []string) {
		appKey := domain.AppKey{
			Organization: organization,
			Name:         appName,
			Version:      appVersion,
		}

		err := services.AppService.DeleteApp(context.Background(), region, appKey)
		if err != nil {
			fmt.Printf("Error deleting app: %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Application deleted successfully")
	},
}

func init() {
	rootCmd.AddCommand(appCmd)
	appCmd.AddCommand(createAppCmd, showAppCmd, listAppsCmd, deleteAppCmd)

	// Add common flags to all app commands
	appCmds := []*cobra.Command{createAppCmd, showAppCmd, listAppsCmd, deleteAppCmd}
	for _, cmd := range appCmds {
		cmd.Flags().StringVarP(&organization, "org", "o", "", "organization name (required)")
		cmd.Flags().StringVarP(&appName, "name", "n", "", "application name")
		cmd.Flags().StringVarP(&appVersion, "version", "v", "", "application version")
		cmd.Flags().StringVarP(&region, "region", "r", "", "region (required)")
		cmd.MarkFlagRequired("org")
		cmd.MarkFlagRequired("region")
	}

	// Add required name flag for specific commands
	for _, cmd := range []*cobra.Command{createAppCmd, showAppCmd, deleteAppCmd} {
		cmd.MarkFlagRequired("name")
	}
}