package drive

import (
	"context"
	"path"

	"github.com/ultisuite/ulti-backend/internal/automation"
	"github.com/ultisuite/ulti-backend/internal/filescan"
	"github.com/ultisuite/ulti-backend/internal/mail/rules"
	"github.com/ultisuite/ulti-backend/internal/nextcloud"
)

func (s *Service) SetAutomation(d driveAutomation) {
	s.automation = d
}

func (s *Service) SetFileScanner(scanner *filescan.Scanner) {
	s.scanner = scanner
}

func (s *Service) afterDriveFileEvent(ctx context.Context, externalUserID string, trigger rules.TriggerType, filePath string, isFolder bool) {
	normalized := nextcloud.NormalizeClientPath(filePath)
	s.notifyFileChanged(externalUserID, normalized)
	if s.automation == nil {
		return
	}
	s.automation.OnDriveEvent(ctx, externalUserID, trigger, automation.DrivePayloadFromPath(normalized, isFolder))
}

func (s *Service) afterDriveShareEvent(ctx context.Context, externalUserID string, filePath string) {
	normalized := nextcloud.NormalizeClientPath(filePath)
	s.notifyShareUpdated(externalUserID, normalized)
	if s.automation == nil {
		return
	}
	s.automation.OnDriveEvent(ctx, externalUserID, rules.TriggerDriveShareUpdated, automation.DrivePayloadFromPath(normalized, false))
}

func renamedPath(oldPath, newName string) string {
	dir := path.Dir(nextcloud.NormalizeClientPath(oldPath))
	if dir == "." || dir == "" {
		dir = "/"
	}
	return nextcloud.NormalizeClientPath(path.Join(dir, newName))
}
