package volume

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"strings"
	"time"
)

// FileEntry represents a single file or directory in a volume listing.
type FileEntry struct {
	Name    string    `json:"name"`
	IsDir   bool      `json:"is_dir"`
	Size    int64     `json:"size"`
	ModTime time.Time `json:"mod_time"`
}

// ListDir returns the contents of a directory within a volume root.
// The relativePath is validated to stay within rootPath.
func ListDir(rootPath, relativePath string) ([]FileEntry, error) {
	absPath, err := safePath(rootPath, relativePath)
	if err != nil {
		return nil, err
	}

	info, err := os.Stat(absPath)
	if err != nil {
		if os.IsNotExist(err) {
			return []FileEntry{}, nil
		}
		return nil, fmt.Errorf("stat directory: %w", err)
	}
	if !info.IsDir() {
		return nil, fmt.Errorf("path is not a directory")
	}

	entries, err := os.ReadDir(absPath)
	if err != nil {
		return nil, fmt.Errorf("read directory: %w", err)
	}

	result := make([]FileEntry, 0, len(entries))
	for _, e := range entries {
		info, err := e.Info()
		if err != nil {
			continue
		}
		result = append(result, FileEntry{
			Name:    e.Name(),
			IsDir:   e.IsDir(),
			Size:    info.Size(),
			ModTime: info.ModTime().UTC(),
		})
	}
	return result, nil
}

// OpenFile opens a file within the volume root for reading.
// The caller is responsible for closing the returned file.
func OpenFile(rootPath, relativePath string) (*os.File, os.FileInfo, error) {
	absPath, err := safePath(rootPath, relativePath)
	if err != nil {
		return nil, nil, err
	}

	info, err := os.Stat(absPath)
	if err != nil {
		return nil, nil, fmt.Errorf("stat file: %w", err)
	}
	if info.IsDir() {
		return nil, nil, fmt.Errorf("path is a directory, use download as zip")
	}

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

// WriteZip writes the contents of a directory (or the entire root) as a zip archive to w.
func WriteZip(rootPath, relativePath string, w io.Writer) error {
	absPath, err := safePath(rootPath, relativePath)
	if err != nil {
		return err
	}

	info, err := os.Stat(absPath)
	if err != nil {
		return fmt.Errorf("stat path: %w", err)
	}
	if !info.IsDir() {
		return fmt.Errorf("path is not a directory")
	}

	zw := zip.NewWriter(w)
	defer zw.Close()

	return filepath.Walk(absPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		rel, err := filepath.Rel(absPath, path)
		if err != nil {
			return err
		}
		if rel == "." {
			return nil
		}
		// Use forward slashes in zip entries.
		rel = filepath.ToSlash(rel)

		if info.IsDir() {
			_, err := zw.Create(rel + "/")
			return err
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}
		header.Name = rel
		header.Method = zip.Deflate

		writer, err := zw.CreateHeader(header)
		if err != nil {
			return err
		}

		f, err := os.Open(path)
		if err != nil {
			return err
		}
		defer f.Close()

		_, err = io.Copy(writer, f)
		return err
	})
}

// SaveFile writes uploaded content to a file within the volume root.
func SaveFile(rootPath, relativePath string, r io.Reader) error {
	absPath, err := safePath(rootPath, relativePath)
	if err != nil {
		return err
	}

	// Ensure parent directory exists.
	dir := filepath.Dir(absPath)
	if err := os.MkdirAll(dir, 0o755); err != nil {
		return fmt.Errorf("create directory: %w", err)
	}

	f, err := os.Create(absPath)
	if err != nil {
		return fmt.Errorf("create file: %w", err)
	}
	defer f.Close()

	if _, err := io.Copy(f, r); err != nil {
		return fmt.Errorf("write file: %w", err)
	}
	return nil
}

// safePath resolves a relative path within rootPath and validates it doesn't escape.
// Resolves symlinks to prevent symlink-based traversal attacks.
func safePath(rootPath, relativePath string) (string, error) {
	if relativePath == "" {
		return rootPath, nil
	}

	// Clean and ensure no traversal.
	cleaned := filepath.Clean(relativePath)
	if strings.Contains(cleaned, "..") {
		return "", fmt.Errorf("path traversal not allowed")
	}

	absPath := filepath.Join(rootPath, cleaned)

	// Resolve the root path (follow symlinks in the root itself).
	absRoot, err := filepath.Abs(rootPath)
	if err != nil {
		return "", fmt.Errorf("resolve root: %w", err)
	}
	if realRoot, err := filepath.EvalSymlinks(absRoot); err == nil {
		absRoot = realRoot
	}

	// Resolve the target path including symlinks.
	absResolved, err := filepath.Abs(absPath)
	if err != nil {
		return "", fmt.Errorf("resolve path: %w", err)
	}
	if realResolved, err := filepath.EvalSymlinks(absResolved); err == nil {
		absResolved = realResolved
	}

	if !strings.HasPrefix(absResolved, absRoot) {
		return "", fmt.Errorf("path traversal not allowed")
	}

	return absPath, nil
}
