package mappers

import (
	"apskel-pos-be/internal/constants"
	"apskel-pos-be/internal/entities"
	"apskel-pos-be/internal/models"
	"strings"

	"fmt"
	"github.com/google/uuid"
)

func FileEntityToResponse(file *entities.File) *models.FileResponse {
	if file == nil {
		return nil
	}

	return &models.FileResponse{
		ID:             file.ID,
		OrganizationID: file.OrganizationID,
		UserID:         file.UserID,
		FileName:       file.FileName,
		OriginalName:   file.OriginalName,
		FileURL:        file.FileURL,
		FileSize:       file.FileSize,
		MimeType:       file.MimeType,
		FileType:       file.FileType,
		UploadPath:     file.UploadPath,
		IsPublic:       file.IsPublic,
		Metadata:       map[string]interface{}(file.Metadata),
		CreatedAt:      file.CreatedAt,
		UpdatedAt:      file.UpdatedAt,
	}
}

func UploadFileRequestToEntity(req *models.UploadFileRequest, organizationID, userID uuid.UUID, fileName, originalName, fileURL, mimeType, uploadPath string, fileSize int64) *entities.File {
	if req == nil {
		return nil
	}

	isPublic := true
	if req.IsPublic != nil {
		isPublic = *req.IsPublic
	}

	return &entities.File{
		OrganizationID: organizationID,
		UserID:         userID,
		FileName:       fileName,
		OriginalName:   originalName,
		FileURL:        fileURL,
		FileSize:       fileSize,
		MimeType:       mimeType,
		FileType:       string(req.FileType),
		UploadPath:     uploadPath,
		IsPublic:       isPublic,
		Metadata:       entities.Metadata(req.Metadata),
	}
}

// Update request to entity updates
func UpdateFileRequestToEntityUpdates(req *models.UpdateFileRequest) map[string]interface{} {
	updates := make(map[string]interface{})

	if req.IsPublic != nil {
		updates["is_public"] = *req.IsPublic
	}
	if req.Metadata != nil {
		updates["metadata"] = entities.Metadata(req.Metadata)
	}

	return updates
}

func FileEntitiesToResponses(files []*entities.File) []*models.FileResponse {
	if files == nil {
		return nil
	}

	responses := make([]*models.FileResponse, len(files))
	for i, file := range files {
		response := FileEntityToResponse(file)
		if response != nil {
			responses[i] = response
		}
	}

	return responses
}

func GenerateFileName(originalName string, organizationID, userID uuid.UUID) string {
	cleanedName := strings.ReplaceAll(originalName, " ", "")
	return fmt.Sprintf("/public/%s_%s", organizationID.String(), cleanedName)
}

func GetFileTypeFromMimeType(mimeType string) constants.FileType {
	return constants.GetFileTypeFromMimeType(mimeType)
}
