package boxstore

import (
	"os"
	"sort"

	"warpbox/lib/helpers"
	"warpbox/lib/models"
)

func ListBoxSummaries() ([]models.BoxSummary, error) {
	entries, err := os.ReadDir(uploadRoot)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}

	summaries := make([]models.BoxSummary, 0, len(entries))
	for _, entry := range entries {
		if !entry.IsDir() || !ValidBoxID(entry.Name()) {
			continue
		}

		summary, err := BoxSummary(entry.Name())
		if err != nil {
			continue
		}
		summaries = append(summaries, summary)
	}

	sort.Slice(summaries, func(i int, j int) bool {
		return summaries[i].CreatedAt.After(summaries[j].CreatedAt)
	})
	return summaries, nil
}

func BoxSummary(boxID string) (models.BoxSummary, error) {
	files, err := ListFiles(boxID)
	if err != nil {
		return models.BoxSummary{}, err
	}

	var manifest models.BoxManifest
	hasManifest := false
	if readManifest, err := ReadManifest(boxID); err == nil {
		manifest = readManifest
		hasManifest = true
	}

	totalSize := int64(0)
	for _, file := range files {
		totalSize += file.Size
	}

	summary := models.BoxSummary{
		ID:             boxID,
		FileCount:      len(files),
		TotalSize:      totalSize,
		TotalSizeLabel: helpers.FormatBytes(totalSize),
	}
	if hasManifest {
		summary.CreatedAt = manifest.CreatedAt
		summary.ExpiresAt = manifest.ExpiresAt
		summary.Expired = IsExpired(manifest)
		summary.OneTimeDownload = manifest.OneTimeDownload
		summary.PasswordProtected = IsPasswordProtected(manifest)
	} else if info, err := os.Stat(BoxPath(boxID)); err == nil {
		summary.CreatedAt = info.ModTime().UTC()
	}

	return summary, nil
}
