package network

import (
	"context"
	"errors"
	"fmt"
	"io/fs"
	"isle/jsonutil"
	"isle/toolkit"
	"os"
	"path/filepath"

	"dev.mediocregopher.com/mediocre-go-lib.git/mctx"
	"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
)

// DEPRECATED
func migrateToMultiNetworkStateDirectory(
	ctx context.Context,
	logger *mlog.Logger,
	stateDir toolkit.Dir,
) error {
	var (
		legacyBootstrapPath = filepath.Join(stateDir.Path, "bootstrap.json")
		legacySecretsPath   = filepath.Join(stateDir.Path, "secrets")
	)

	if _, err := os.Stat(legacyBootstrapPath); errors.Is(err, fs.ErrNotExist) {
		return nil // no bootstrap in the legacy path
	} else if err != nil {
		return fmt.Errorf("checking file %q: %w", legacyBootstrapPath, err)
	}

	var bootstrapBody struct {
		NetworkCreationParams struct {
			ID string
		}
	}

	if err := jsonutil.LoadFile(
		&bootstrapBody, legacyBootstrapPath,
	); err != nil {
		return fmt.Errorf(
			"loading bootstrap from %q: %w", legacyBootstrapPath, err,
		)
	}

	var (
		networkStateDirPath = filepath.Join(
			stateDir.Path, "networks", bootstrapBody.NetworkCreationParams.ID,
		)

		newBootstrapPath = filepath.Join(networkStateDirPath, "bootstrap.json")
		newSecretsPath   = filepath.Join(networkStateDirPath, "secrets")
	)

	ctx = mctx.Annotate(
		ctx,
		"legacyBootstrapPath", legacyBootstrapPath,
		"legacySecretsPath", legacySecretsPath,
		"newBootstrapPath", newBootstrapPath,
		"newSecretsPath", newSecretsPath,
	)

	logger.Info(ctx, "Migrating to multi-network state directory layout")

	if err := os.MkdirAll(networkStateDirPath, 0700); err != nil {
		return fmt.Errorf("creating %q: %w", networkStateDirPath, err)
	}

	if err := os.Rename(legacyBootstrapPath, newBootstrapPath); err != nil {
		return fmt.Errorf(
			"renaming %q to %q: %w", legacyBootstrapPath, newBootstrapPath, err,
		)
	}

	if err := os.Rename(legacySecretsPath, newSecretsPath); err != nil {
		return fmt.Errorf(
			"renaming %q to %q: %w", legacySecretsPath, newSecretsPath, err,
		)
	}

	return nil
}