// monorepo/cloud/maplefile-backend/internal/maplefile/repo/filemetadata/impl.go
package filemetadata

import (
	"encoding/json"

	"github.com/gocql/gocql"
	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/config"
	dom_collection "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/collection"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/crypto"
	dom_file "codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/file"
	"codeberg.org/mapleopentech/monorepo/cloud/maplefile-backend/internal/domain/tag"
)

type fileMetadataRepositoryImpl struct {
	Logger         *zap.Logger
	Session        *gocql.Session
	CollectionRepo dom_collection.CollectionRepository
}

func NewRepository(appCfg *config.Configuration, session *gocql.Session, loggerp *zap.Logger, collectionRepo dom_collection.CollectionRepository) dom_file.FileMetadataRepository {
	loggerp = loggerp.Named("FileMetadataRepository")

	return &fileMetadataRepositoryImpl{
		Logger:         loggerp,
		Session:        session,
		CollectionRepo: collectionRepo,
	}
}

// Helper functions for JSON serialization
func (impl *fileMetadataRepositoryImpl) serializeEncryptedFileKey(key crypto.EncryptedFileKey) (string, error) {
	data, err := json.Marshal(key)
	return string(data), err
}

func (impl *fileMetadataRepositoryImpl) deserializeEncryptedFileKey(data string) (crypto.EncryptedFileKey, error) {
	if data == "" {
		return crypto.EncryptedFileKey{}, nil
	}
	var key crypto.EncryptedFileKey
	err := json.Unmarshal([]byte(data), &key)
	return key, err
}

func (impl *fileMetadataRepositoryImpl) serializeTags(tags []tag.EmbeddedTag) (string, error) {
	if len(tags) == 0 {
		return "[]", nil
	}
	data, err := json.Marshal(tags)
	return string(data), err
}

func (impl *fileMetadataRepositoryImpl) deserializeTags(data string) ([]tag.EmbeddedTag, error) {
	if data == "" || data == "[]" {
		return []tag.EmbeddedTag{}, nil
	}
	var tags []tag.EmbeddedTag
	err := json.Unmarshal([]byte(data), &tags)
	return tags, err
}

// isValidUUID checks if UUID is not nil/empty
func (impl *fileMetadataRepositoryImpl) isValidUUID(id gocql.UUID) bool {
	return id.String() != "00000000-0000-0000-0000-000000000000"
}
