package storage

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

type LocalStore struct {
	rootDir string
	tempDir string
}

func NewLocal(rootDir string) (*LocalStore, error) {
	rootDir = filepath.Clean(rootDir)
	tempDir := filepath.Join(rootDir, ".tmp")

	for _, dir := range []string{rootDir, tempDir} {
		if err := os.MkdirAll(dir, 0o750); err != nil {
			return nil, fmt.Errorf("create artifact directory %s: %w", dir, err)
		}
	}

	return &LocalStore{
		rootDir: rootDir,
		tempDir: tempDir,
	}, nil
}

func (s *LocalStore) RootDir() string {
	return s.rootDir
}

func (s *LocalStore) CreateTemp(pattern string) (*os.File, string, error) {
	file, err := os.CreateTemp(s.tempDir, pattern)
	if err != nil {
		return nil, "", fmt.Errorf("create temp file: %w", err)
	}

	return file, file.Name(), nil
}

func (s *LocalStore) CommitTemp(tempPath, relativePath string) error {
	destination, err := s.absolutePath(relativePath)
	if err != nil {
		return err
	}

	if err := os.MkdirAll(filepath.Dir(destination), 0o750); err != nil {
		return fmt.Errorf("create artifact parent directory: %w", err)
	}

	if _, err := os.Stat(destination); err == nil {
		return fmt.Errorf("artifact already exists at %s", relativePath)
	} else if !os.IsNotExist(err) {
		return fmt.Errorf("check artifact destination: %w", err)
	}

	if err := os.Rename(tempPath, destination); err != nil {
		return fmt.Errorf("move artifact into place: %w", err)
	}

	return nil
}

func (s *LocalStore) Remove(relativePath string) error {
	destination, err := s.absolutePath(relativePath)
	if err != nil {
		return err
	}

	if err := os.Remove(destination); err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("remove artifact: %w", err)
	}

	return nil
}

func (s *LocalStore) RemoveTemp(tempPath string) error {
	if strings.TrimSpace(tempPath) == "" {
		return nil
	}

	if err := os.Remove(tempPath); err != nil && !os.IsNotExist(err) {
		return fmt.Errorf("remove temp artifact: %w", err)
	}

	return nil
}

func (s *LocalStore) Open(relativePath string) (*os.File, error) {
	destination, err := s.absolutePath(relativePath)
	if err != nil {
		return nil, err
	}

	file, err := os.Open(destination)
	if err != nil {
		return nil, fmt.Errorf("open artifact: %w", err)
	}

	return file, nil
}

func (s *LocalStore) absolutePath(relativePath string) (string, error) {
	relativePath = filepath.Clean(strings.TrimSpace(relativePath))
	if relativePath == "." || relativePath == "" {
		return "", fmt.Errorf("artifact path is required")
	}

	if filepath.IsAbs(relativePath) {
		return "", fmt.Errorf("artifact path must be relative")
	}

	joined := filepath.Join(s.rootDir, relativePath)
	rel, err := filepath.Rel(s.rootDir, joined)
	if err != nil {
		return "", fmt.Errorf("resolve artifact path: %w", err)
	}

	if rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
		return "", fmt.Errorf("artifact path escapes storage root")
	}

	return joined, nil
}
