package persist

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	log "github.com/crc-org/crc/v2/pkg/crc/logging"
	"github.com/crc-org/crc/v2/pkg/libmachine/host"
)

type Filestore struct {
	MachinesDir string
}

func NewFilestore(path string) *Filestore {
	return &Filestore{
		MachinesDir: filepath.Join(path, "machines"),
	}
}

func (s Filestore) saveToFile(data []byte, file string) error {
	if _, err := os.Stat(file); os.IsNotExist(err) {
		return os.WriteFile(file, data, 0600)
	}

	rootDir, err := os.OpenRoot(filepath.Dir(file))
	if err != nil {
		return err
	}
	defer rootDir.Close()
	fileFilename := filepath.Base(file)

	tmpFile, err := os.CreateTemp(rootDir.Name(), "config.json.tmp")
	if err != nil {
		return err
	}
	defer tmpFile.Close()
	tmpFileFilename := filepath.Base(tmpFile.Name())

	if err = rootDir.WriteFile(tmpFileFilename, data, 0600); err != nil {
		return err
	}

	if err = tmpFile.Close(); err != nil {
		return err
	}

	if err = rootDir.Rename(tmpFileFilename, fileFilename); err != nil {
		return err
	}

	return nil
}

func (s Filestore) Save(host *host.Host) error {
	data, err := json.MarshalIndent(host, "", "    ")
	if err != nil {
		return err
	}

	hostPath := filepath.Join(s.MachinesDir, host.Name)

	// Ensure that the directory we want to save to exists.
	if err := os.MkdirAll(hostPath, 0700); err != nil {
		return err
	}

	return s.saveToFile(data, filepath.Join(hostPath, "config.json"))
}

func (s Filestore) Remove(name string) error {
	hostPath := filepath.Join(s.MachinesDir, name)
	return os.RemoveAll(hostPath)
}

func (s Filestore) SetExists(name string) error {
	filename := filepath.Join(s.MachinesDir, name, fmt.Sprintf(".%s-exist", name))
	file, err := os.OpenFile(filename, os.O_RDONLY|os.O_CREATE, 0666)
	if err != nil {
		return err
	}
	file.Close()
	log.Debugf("Created %s", filename)

	return nil
}

func (s Filestore) Exists(name string) (bool, error) {
	filename := filepath.Join(s.MachinesDir, name, fmt.Sprintf(".%s-exist", name))
	_, err := os.Stat(filename)

	if os.IsNotExist(err) {
		log.Debugf("file not found: %s", filename)
		return false, nil
	} else if err == nil {
		return true, nil
	}

	return false, err
}

func (s Filestore) Load(name string) (*host.Host, error) {
	hostPath := filepath.Join(s.MachinesDir, name)

	if _, err := os.Stat(hostPath); os.IsNotExist(err) {
		return nil, fmt.Errorf("machine %s does not exist", name)
	}
	data, err := os.ReadFile(filepath.Join(s.MachinesDir, name, "config.json"))
	if err != nil {
		return nil, err
	}
	return host.MigrateHost(name, data)
}
