// codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/usecase/filemetadata/list_by_owner.go
package filemetadata

import (
	"context"

	"go.uber.org/zap"

	"github.com/gocql/gocql"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	dom_file "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/file"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/pkg/httperror"
)

type ListFilesByOwnerIDUseCase interface {
	Execute(ctx context.Context, ownerID gocql.UUID) ([]*dom_file.File, error)
}

type listFilesByOwnerIDUseCaseImpl struct {
	config *config.Configuration
	logger *zap.Logger
	repo   dom_file.FileMetadataRepository
}

func NewListFilesByOwnerIDUseCase(
	config *config.Configuration,
	logger *zap.Logger,
	repo dom_file.FileMetadataRepository,
) ListFilesByOwnerIDUseCase {
	logger = logger.Named("ListFilesByOwnerIDUseCase")
	return &listFilesByOwnerIDUseCaseImpl{config, logger, repo}
}

func (uc *listFilesByOwnerIDUseCaseImpl) Execute(ctx context.Context, ownerID gocql.UUID) ([]*dom_file.File, error) {
	//
	// STEP 1: Validation.
	//

	e := make(map[string]string)
	if ownerID.String() == "" {
		e["owner_id"] = "Owner ID is required"
	}
	if len(e) != 0 {
		uc.logger.Warn("Failed validating list files by owner",
			zap.Any("error", e))
		return nil, httperror.NewForBadRequest(&e)
	}

	//
	// STEP 2: Get from database.
	//

	files, err := uc.repo.GetByOwnerID(ownerID)
	if err != nil {
		uc.logger.Error("Failed to get files by owner ID",
			zap.String("owner_id", ownerID.String()),
			zap.Error(err))
		return nil, err
	}

	uc.logger.Debug("Files successfully retrieved by owner ID",
		zap.String("owner_id", ownerID.String()),
		zap.Int("count", len(files)))

	return files, nil
}
