package listing

import (
	"net/url"
	"os"
)

// FromDirEntries converts os.DirEntry slice to []FileInfo.
// baseURL is the URL prefix for this directory (must end with "/").
// When includeHidden is false (the default for normal listings),
// entries starting with "." or "_" are excluded. When true (the
// dispatcher passes ?hidden=1 through to here), they're surfaced;
// the caller is responsible for any further policy gating, but
// in practice the existing ACL chain on the parent directory is
// the only gate that matters.
func FromDirEntries(entries []os.DirEntry, baseURL string, includeHidden bool) ([]FileInfo, error) {
	var result []FileInfo
	for _, entry := range entries {
		name := entry.Name()

		// Skip empty names always. '.' and '_' prefixes mark hidden
		// entries — system/internal state (.zddc, .converted/,
		// .zddc.d/) and operator scaffolding (_app, _template). These
		// are filtered by default; pass includeHidden=true to expose.
		if len(name) == 0 {
			continue
		}
		if !includeHidden && (name[0] == '.' || name[0] == '_') {
			continue
		}

		info, err := entry.Info()
		if err != nil {
			continue
		}

		isDir := entry.IsDir()
		entryName := name
		entryURL := baseURL + url.PathEscape(name)
		if isDir {
			entryName = name + "/"
			entryURL = baseURL + url.PathEscape(name) + "/"
		}

		fi := FileInfo{
			Name:      entryName,
			Size:      info.Size(),
			URL:       entryURL,
			ModTime:   info.ModTime(),
			Mode:      uint32(info.Mode()),
			IsDir:     isDir,
			IsSymlink: false,
		}
		result = append(result, fi)
	}
	return result, nil
}
