package app

import (
	"context"
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"

	"coopcloud.tech/abra/cli/internal"
	appPkg "coopcloud.tech/abra/pkg/app"
	"coopcloud.tech/abra/pkg/autocomplete"
	"coopcloud.tech/abra/pkg/client"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/log"
	"coopcloud.tech/abra/pkg/secret"
	"github.com/docker/docker/api/types"
	dockerClient "github.com/docker/docker/client"
	"github.com/urfave/cli/v3"
)

var (
	allSecrets     bool
	allSecretsFlag = &cli.BoolFlag{
		Name:        "all",
		Aliases:     []string{"a"},
		Destination: &allSecrets,
		Usage:       "Generate all secrets",
	}
)

var (
	rmAllSecrets     bool
	rmAllSecretsFlag = &cli.BoolFlag{
		Name:        "all",
		Aliases:     []string{"a"},
		Destination: &rmAllSecrets,
		Usage:       "Remove all secrets",
	}
)

var appSecretGenerateCommand = cli.Command{
	Name:      "generate",
	Aliases:   []string{"g"},
	Usage:     "Generate secrets",
	UsageText: "abra app secret generate <domain> <secret> <version> [options]",
	Flags: []cli.Flag{
		allSecretsFlag,
		internal.PassFlag,
		internal.MachineReadableFlag,
		internal.ChaosFlag,
	},
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.AppNameComplete,
	HideHelp:      true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		app := internal.ValidateApp(cmd)
		if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil {
			log.Fatal(err)
		}

		if cmd.Args().Len() == 1 && !allSecrets {
			err := errors.New("missing arguments <secret>/<version> or '--all'")
			internal.ShowSubcommandHelpAndError(cmd, err)
		}

		if cmd.Args().Get(1) != "" && allSecrets {
			err := errors.New("cannot use '<secret> <version>' and '--all' together")
			internal.ShowSubcommandHelpAndError(cmd, err)
		}

		composeFiles, err := app.Recipe.GetComposeFiles(app.Env)
		if err != nil {
			log.Fatal(err)
		}

		secrets, err := secret.ReadSecretsConfig(app.Path, composeFiles, app.StackName())
		if err != nil {
			log.Fatal(err)
		}

		if !allSecrets {
			secretName := cmd.Args().Get(1)
			secretVersion := cmd.Args().Get(2)
			s, ok := secrets[secretName]
			if !ok {
				log.Fatalf("%s doesn't exist in the env config?", secretName)
			}
			s.Version = secretVersion
			secrets = map[string]secret.Secret{
				secretName: s,
			}
		}

		cl, err := client.New(app.Server)
		if err != nil {
			log.Fatal(err)
		}

		secretVals, err := secret.GenerateSecrets(cl, secrets, app.Server)
		if err != nil {
			log.Fatal(err)
		}

		if internal.Pass {
			for name, data := range secretVals {
				if err := secret.PassInsertSecret(data, name, app.Name, app.Server); err != nil {
					log.Fatal(err)
				}
			}
		}

		if len(secretVals) == 0 {
			log.Warn("no secrets generated")
			os.Exit(1)
		}

		headers := []string{"NAME", "VALUE"}
		table, err := formatter.CreateTable()
		if err != nil {
			log.Fatal(err)
		}

		table.Headers(headers...)

		var rows [][]string
		for name, val := range secretVals {
			row := []string{name, val}
			rows = append(rows, row)
			table.Row(row...)
		}

		if internal.MachineReadable {
			out, err := formatter.ToJSON(headers, rows)
			if err != nil {
				log.Fatal("unable to render to JSON: %s", err)
			}
			fmt.Println(out)
			return nil
		}

		fmt.Println(table)

		log.Warnf(
			"generated secrets %s shown again, please take note of them %s",
			formatter.BoldStyle.Render("NOT"),
			formatter.BoldStyle.Render("NOW"),
		)

		return nil
	},
}

var appSecretInsertCommand = cli.Command{
	Name:      "insert",
	Aliases:   []string{"i"},
	Usage:     "Insert secret",
	UsageText: "abra app secret insert <domain> <secret> <version> <data> [options]",
	Flags: []cli.Flag{
		internal.PassFlag,
		internal.FileFlag,
		internal.TrimFlag,
		internal.ChaosFlag,
	},
	Before:          internal.SubCommandBefore,
	ShellComplete:   autocomplete.AppNameComplete,
	HideHelpCommand: true,
	Description: `This command inserts a secret into an app environment.

This can be useful when you want to manually generate secrets for an app
environment. Typically, you can let Abra generate them for you on app creation
(see "abra app new --secrets" for more).`,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		app := internal.ValidateApp(cmd)
		if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil {
			log.Fatal(err)
		}

		if cmd.Args().Len() != 4 {
			internal.ShowSubcommandHelpAndError(cmd, errors.New("missing arguments?"))
		}

		cl, err := client.New(app.Server)
		if err != nil {
			log.Fatal(err)
		}

		name := cmd.Args().Get(1)
		version := cmd.Args().Get(2)
		data := cmd.Args().Get(3)

		if internal.File {
			raw, err := os.ReadFile(data)
			if err != nil {
				log.Fatalf("reading secret from file: %s", err)
			}
			data = string(raw)
		}

		if internal.Trim {
			data = strings.TrimSpace(data)
		}

		secretName := fmt.Sprintf("%s_%s_%s", app.StackName(), name, version)
		if err := client.StoreSecret(cl, secretName, data, app.Server); err != nil {
			log.Fatal(err)
		}

		log.Infof("%s successfully stored on server", secretName)

		if internal.Pass {
			if err := secret.PassInsertSecret(data, name, app.Name, app.Server); err != nil {
				log.Fatal(err)
			}
		}

		return nil
	},
}

// secretRm removes a secret.
func secretRm(cl *dockerClient.Client, app appPkg.App, secretName, parsed string) error {
	if err := cl.SecretRemove(context.Background(), secretName); err != nil {
		return err
	}

	log.Infof("deleted %s successfully from server", secretName)

	if internal.PassRemove {
		if err := secret.PassRmSecret(parsed, app.StackName(), app.Server); err != nil {
			return err
		}

		log.Infof("deleted %s successfully from local pass store", secretName)
	}

	return nil
}

var appSecretRmCommand = cli.Command{
	Name:      "remove",
	Aliases:   []string{"rm"},
	Usage:     "Remove a secret",
	UsageText: "abra app remove <domainabra app remove <domain> [options]",
	Flags: []cli.Flag{
		internal.NoInputFlag,
		rmAllSecretsFlag,
		internal.PassRemoveFlag,
		internal.OfflineFlag,
		internal.ChaosFlag,
	},
	Before:        internal.SubCommandBefore,
	ShellComplete: autocomplete.AppNameComplete,
	Description: `
This command removes app secrets.

Example:

    abra app secret remove myapp db_pass`,
	HideHelp: true,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		app := internal.ValidateApp(cmd)
		if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil {
			log.Fatal(err)
		}

		composeFiles, err := app.Recipe.GetComposeFiles(app.Env)
		if err != nil {
			log.Fatal(err)
		}

		secrets, err := secret.ReadSecretsConfig(app.Path, composeFiles, app.StackName())
		if err != nil {
			log.Fatal(err)
		}

		if cmd.Args().Get(1) != "" && rmAllSecrets {
			internal.ShowSubcommandHelpAndError(cmd, errors.New("cannot use '<secret-name>' and '--all' together"))
		}

		if cmd.Args().Get(1) == "" && !rmAllSecrets {
			internal.ShowSubcommandHelpAndError(cmd, errors.New("no secret(s) specified?"))
		}

		cl, err := client.New(app.Server)
		if err != nil {
			log.Fatal(err)
		}

		filters, err := app.Filters(false, false)
		if err != nil {
			log.Fatal(err)
		}

		secretList, err := cl.SecretList(context.Background(), types.SecretListOptions{Filters: filters})
		if err != nil {
			log.Fatal(err)
		}

		remoteSecretNames := make(map[string]bool)
		for _, cont := range secretList {
			remoteSecretNames[cont.Spec.Annotations.Name] = true
		}

		match := false
		secretToRm := cmd.Args().Get(1)
		for secretName, val := range secrets {
			secretRemoteName := fmt.Sprintf("%s_%s_%s", app.StackName(), secretName, val.Version)
			if _, ok := remoteSecretNames[secretRemoteName]; ok {
				if secretToRm != "" {
					if secretName == secretToRm {
						if err := secretRm(cl, app, secretRemoteName, secretName); err != nil {
							log.Fatal(err)
						}

						return nil
					}
				} else {
					match = true

					if err := secretRm(cl, app, secretRemoteName, secretName); err != nil {
						log.Fatal(err)
					}
				}
			}
		}

		if !match && secretToRm != "" {
			log.Fatalf("%s doesn't exist on server?", secretToRm)
		}

		if !match {
			log.Fatal("no secrets to remove?")
		}

		return nil
	},
}

var appSecretLsCommand = cli.Command{
	Name:    "list",
	Aliases: []string{"ls"},
	Flags: []cli.Flag{
		internal.OfflineFlag,
		internal.ChaosFlag,
		internal.MachineReadableFlag,
	},
	Before:        internal.SubCommandBefore,
	Usage:         "List all secrets",
	UsageText:     "abra app secret list [options]",
	HideHelp:      true,
	ShellComplete: autocomplete.AppNameComplete,
	Action: func(ctx context.Context, cmd *cli.Command) error {
		app := internal.ValidateApp(cmd)
		if err := app.Recipe.Ensure(internal.Chaos, internal.Offline); err != nil {
			log.Fatal(err)
		}

		cl, err := client.New(app.Server)
		if err != nil {
			log.Fatal(err)
		}

		headers := []string{"NAME", "VERSION", "GENERATED NAME", "CREATED ON SERVER"}
		table, err := formatter.CreateTable()
		if err != nil {
			log.Fatal(err)
		}

		table.Headers(headers...)

		secStats, err := secret.PollSecretsStatus(cl, app)
		if err != nil {
			log.Fatal(err)
		}

		var rows [][]string
		for _, secStat := range secStats {
			row := []string{
				secStat.LocalName,
				secStat.Version,
				secStat.RemoteName,
				strconv.FormatBool(secStat.CreatedOnRemote),
			}

			rows = append(rows, row)
			table.Row(row...)
		}

		if len(rows) > 0 {
			if internal.MachineReadable {
				out, err := formatter.ToJSON(headers, rows)
				if err != nil {
					log.Fatal("unable to render to JSON: %s", err)
				}
				fmt.Println(out)
				return nil
			}

			fmt.Println(table)
			return nil
		}

		log.Warnf("no secrets stored for %s", app.Name)

		return nil
	},
}

var appSecretCommand = cli.Command{
	Name:      "secret",
	Aliases:   []string{"s"},
	Usage:     "Manage app secrets",
	UsageText: "abra app secret [command] [arguments] [options]",
	Commands: []*cli.Command{
		&appSecretGenerateCommand,
		&appSecretInsertCommand,
		&appSecretRmCommand,
		&appSecretLsCommand,
	},
}
