package automation

import (
	"github.com/ultisuite/ulti-backend/internal/apitokens"
)

type MailScope struct {
	AllAccounts bool     `json:"all_accounts"`
	AccountIDs  []string `json:"account_ids"`
}

type DriveScope struct {
	AllFolders  bool     `json:"all_folders"`
	FolderPaths []string `json:"folder_paths"`
}

type ContactsScope struct {
	AllBooks bool     `json:"all_books"`
	BookIDs  []string `json:"book_ids"`
}

func AllowsMailScope(scope MailScope, accountID string) bool {
	if accountID == "" {
		return true
	}
	if scope.AllAccounts {
		return true
	}
	for _, id := range scope.AccountIDs {
		if id == accountID {
			return true
		}
	}
	return false
}

func AllowsDriveScope(scope DriveScope, filePath string) bool {
	if scope.AllFolders {
		return true
	}
	target := apitokens.NormalizeDriveScopePath(filePath)
	if target == "" {
		return true
	}
	for _, allowed := range scope.FolderPaths {
		if apitokens.NormalizeDriveScopePath(allowed) == "/" {
			return true
		}
		if drivePathWithinScope(target, allowed) {
			return true
		}
	}
	return false
}

func drivePathWithinScope(target, allowed string) bool {
	target = apitokens.NormalizeDriveScopePath(target)
	allowed = apitokens.NormalizeDriveScopePath(allowed)
	if allowed == "/" {
		return true
	}
	if target == allowed {
		return true
	}
	return len(target) > len(allowed) && target[:len(allowed)+1] == allowed+"/"
}

func AllowsContactsScope(scope ContactsScope, bookID string) bool {
	if bookID == "" {
		return true
	}
	if scope.AllBooks {
		return true
	}
	for _, id := range scope.BookIDs {
		if id == bookID {
			return true
		}
	}
	return false
}
