package driveroot

import (
	"fmt"
	"strings"

	"github.com/ultisuite/ulti-backend/internal/nextcloud"
)

type Kind string

const (
	KindPersonal Kind = "personal"
	KindOrg      Kind = "org"
	KindMount    Kind = "mount"
)

type Capabilities struct {
	Share   bool `json:"share"`
	Trash   bool `json:"trash"`
	Preview bool `json:"preview"`
}

type Ref struct {
	Kind   Kind   `json:"root_kind"`
	RootID string `json:"root_id,omitempty"`
	Path   string `json:"path"`
}

func Personal(path string) Ref {
	return Ref{Kind: KindPersonal, Path: nextcloud.NormalizeClientPath(path)}
}

func Org(rootID, path string) Ref {
	return Ref{Kind: KindOrg, RootID: strings.TrimSpace(rootID), Path: nextcloud.NormalizeClientPath(path)}
}

func Mount(rootID, path string) Ref {
	return Ref{Kind: KindMount, RootID: strings.TrimSpace(rootID), Path: nextcloud.NormalizeClientPath(path)}
}

func (r Ref) Capabilities() Capabilities {
	switch r.Kind {
	case KindOrg:
		return Capabilities{Share: true, Trash: true, Preview: true}
	case KindMount:
		return Capabilities{Share: true, Trash: false, Preview: true}
	default:
		return Capabilities{Share: true, Trash: true, Preview: true}
	}
}

func ParseKind(raw string) (Kind, error) {
	switch Kind(strings.TrimSpace(strings.ToLower(raw))) {
	case "", KindPersonal:
		return KindPersonal, nil
	case KindOrg:
		return KindOrg, nil
	case KindMount:
		return KindMount, nil
	default:
		return "", fmt.Errorf("invalid root kind")
	}
}

func EnrichFile(file nextcloud.FileInfo, ref Ref) nextcloud.FileInfo {
	file.Source = ""
	cap := ref.Capabilities()
	file.RootKind = string(ref.Kind)
	file.RootID = ref.RootID
	file.Capabilities = &nextcloud.FileCapabilities{
		Share:   cap.Share,
		Trash:   cap.Trash,
		Preview: cap.Preview,
	}
	return file
}

func EnrichFiles(files []nextcloud.FileInfo, ref Ref) []nextcloud.FileInfo {
	out := make([]nextcloud.FileInfo, len(files))
	for i, f := range files {
		out[i] = EnrichFile(f, ref)
	}
	return out
}
