package cmd

import (
	"context"
	"fmt"
	"os"

	"edp.buildth.ing/DevFW-CICD/edge-connect-client/v2/sdk/edgeconnect"
	v2 "edp.buildth.ing/DevFW-CICD/edge-connect-client/v2/sdk/edgeconnect/v2"
	"github.com/spf13/cobra"
)

var (
	cloudletName string
	cloudletOrg  string
	instanceName string
	flavorName   string
	appId        string
)

var appInstanceCmd = &cobra.Command{
	Use:   "instance",
	Short: "Manage Edge Connect application instances",
	Long:  `Create, show, list, and delete Edge Connect application instances.`,
}

var createInstanceCmd = &cobra.Command{
	Use:   "create",
	Short: "Create a new Edge Connect application instance",
	Run: func(cmd *cobra.Command, args []string) {
		apiVersion := getAPIVersion()
		var err error

		if apiVersion == "v1" {
			c := newSDKClientV1()
			input := &edgeconnect.NewAppInstanceInput{
				Region: region,
				AppInst: edgeconnect.AppInstance{
					Key: edgeconnect.AppInstanceKey{
						Organization: organization,
						Name:         instanceName,
						CloudletKey: edgeconnect.CloudletKey{
							Organization: cloudletOrg,
							Name:         cloudletName,
						},
					},
					AppKey: edgeconnect.AppKey{
						Organization: organization,
						Name:         appName,
						Version:      appVersion,
					},
					Flavor: edgeconnect.Flavor{
						Name: flavorName,
					},
				},
			}
			err = c.CreateAppInstance(context.Background(), input)
		} else {
			c := newSDKClientV2()
			input := &v2.NewAppInstanceInput{
				Region: region,
				AppInst: v2.AppInstance{
					Key: v2.AppInstanceKey{
						Organization: organization,
						Name:         instanceName,
						CloudletKey: v2.CloudletKey{
							Organization: cloudletOrg,
							Name:         cloudletName,
						},
					},
					AppKey: v2.AppKey{
						Organization: organization,
						Name:         appName,
						Version:      appVersion,
					},
					Flavor: v2.Flavor{
						Name: flavorName,
					},
				},
			}
			err = c.CreateAppInstance(context.Background(), input)
		}

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

var showInstanceCmd = &cobra.Command{
	Use:   "show",
	Short: "Show details of an Edge Connect application instance",
	Run: func(cmd *cobra.Command, args []string) {
		apiVersion := getAPIVersion()

		if apiVersion == "v1" {
			c := newSDKClientV1()
			instanceKey := edgeconnect.AppInstanceKey{
				Organization: organization,
				Name:         instanceName,
				CloudletKey: edgeconnect.CloudletKey{
					Organization: cloudletOrg,
					Name:         cloudletName,
				},
			}
			appkey := edgeconnect.AppKey{Name: appId}
			instance, err := c.ShowAppInstance(context.Background(), instanceKey, appkey, region)
			if err != nil {
				fmt.Printf("Error showing app instance: %v\n", err)
				os.Exit(1)
			}
			fmt.Printf("Application instance details:\n%+v\n", instance)
		} else {
			c := newSDKClientV2()
			instanceKey := v2.AppInstanceKey{
				Organization: organization,
				Name:         instanceName,
				CloudletKey: v2.CloudletKey{
					Organization: cloudletOrg,
					Name:         cloudletName,
				},
			}
			appkey := v2.AppKey{Name: appId}
			instance, err := c.ShowAppInstance(context.Background(), instanceKey, appkey, region)
			if err != nil {
				fmt.Printf("Error showing app instance: %v\n", err)
				os.Exit(1)
			}
			fmt.Printf("Application instance details:\n%+v\n", instance)
		}
	},
}

var listInstancesCmd = &cobra.Command{
	Use:   "list",
	Short: "List Edge Connect application instances",
	Run: func(cmd *cobra.Command, args []string) {
		apiVersion := getAPIVersion()

		if apiVersion == "v1" {
			c := newSDKClientV1()
			instanceKey := edgeconnect.AppInstanceKey{
				Organization: organization,
				Name:         instanceName,
				CloudletKey: edgeconnect.CloudletKey{
					Organization: cloudletOrg,
					Name:         cloudletName,
				},
			}
			appKey := edgeconnect.AppKey{Name: appId}
			instances, err := c.ShowAppInstances(context.Background(), instanceKey, appKey, region)
			if err != nil {
				fmt.Printf("Error listing app instances: %v\n", err)
				os.Exit(1)
			}
			fmt.Println("Application instances:")
			for _, instance := range instances {
				fmt.Printf("%+v\n", instance)
			}
		} else {
			c := newSDKClientV2()
			instanceKey := v2.AppInstanceKey{
				Organization: organization,
				Name:         instanceName,
				CloudletKey: v2.CloudletKey{
					Organization: cloudletOrg,
					Name:         cloudletName,
				},
			}
			appKey := v2.AppKey{Name: appId}
			instances, err := c.ShowAppInstances(context.Background(), instanceKey, appKey, region)
			if err != nil {
				fmt.Printf("Error listing app instances: %v\n", err)
				os.Exit(1)
			}
			fmt.Println("Application instances:")
			for _, instance := range instances {
				fmt.Printf("%+v\n", instance)
			}
		}
	},
}

var deleteInstanceCmd = &cobra.Command{
	Use:   "delete",
	Short: "Delete an Edge Connect application instance",
	Run: func(cmd *cobra.Command, args []string) {
		apiVersion := getAPIVersion()
		var err error

		if apiVersion == "v1" {
			c := newSDKClientV1()
			instanceKey := edgeconnect.AppInstanceKey{
				Organization: organization,
				Name:         instanceName,
				CloudletKey: edgeconnect.CloudletKey{
					Organization: cloudletOrg,
					Name:         cloudletName,
				},
			}
			err = c.DeleteAppInstance(context.Background(), instanceKey, region)
		} else {
			c := newSDKClientV2()
			instanceKey := v2.AppInstanceKey{
				Organization: organization,
				Name:         instanceName,
				CloudletKey: v2.CloudletKey{
					Organization: cloudletOrg,
					Name:         cloudletName,
				},
			}
			err = c.DeleteAppInstance(context.Background(), instanceKey, region)
		}

		if err != nil {
			fmt.Printf("Error deleting app instance: %v\n", err)
			os.Exit(1)
		}
		fmt.Println("Application instance deleted successfully")
	},
}

func init() {
	rootCmd.AddCommand(appInstanceCmd)
	appInstanceCmd.AddCommand(createInstanceCmd, showInstanceCmd, listInstancesCmd, deleteInstanceCmd)

	// Add flags to all instance commands
	instanceCmds := []*cobra.Command{createInstanceCmd, showInstanceCmd, listInstancesCmd, deleteInstanceCmd}
	for _, cmd := range instanceCmds {
		cmd.Flags().StringVarP(&organization, "org", "o", "", "organization name (required)")
		cmd.Flags().StringVarP(&instanceName, "name", "n", "", "instance name (required)")
		cmd.Flags().StringVarP(&cloudletName, "cloudlet", "c", "", "cloudlet name (required)")
		cmd.Flags().StringVarP(&cloudletOrg, "cloudlet-org", "", "", "cloudlet organization (required)")
		cmd.Flags().StringVarP(&region, "region", "r", "", "region (required)")
		cmd.Flags().StringVarP(&appId, "app-id", "i", "", "application id")

		if err := cmd.MarkFlagRequired("org"); err != nil {
			panic(err)
		}
		if err := cmd.MarkFlagRequired("name"); err != nil {
			panic(err)
		}
		if err := cmd.MarkFlagRequired("cloudlet"); err != nil {
			panic(err)
		}
		if err := cmd.MarkFlagRequired("cloudlet-org"); err != nil {
			panic(err)
		}
		if err := cmd.MarkFlagRequired("region"); err != nil {
			panic(err)
		}
	}

	// Add additional flags for create command
	createInstanceCmd.Flags().StringVarP(&appName, "app", "a", "", "application name (required)")
	createInstanceCmd.Flags().StringVarP(&appVersion, "version", "v", "", "application version")
	createInstanceCmd.Flags().StringVarP(&flavorName, "flavor", "f", "", "flavor name (required)")
	if err := createInstanceCmd.MarkFlagRequired("app"); err != nil {
		panic(err)
	}
	if err := createInstanceCmd.MarkFlagRequired("flavor"); err != nil {
		panic(err)
	}
}
