using Butter.Dtos;
using Lactose.Context;
using Lactose.Models;

namespace Lactose.Repositories;

public class MediaRepository(LactoseDbContext context) : IMediaRepository {
    /// <summary>
    /// Trys to get the asset with the given ID, and checks if it is shared with the given user or public.
    /// </summary>
    /// <param name="id">Asset ID</param>
    /// <param name="userId">UserID we are trying to get this as</param>
    /// <returns></returns>
    Asset? GetAssetAsUserId(Guid id, Guid? userId) {
        // Should be equivalent to:
        //    media.IsPubliclyShared && media.SharedWith.Any(user => user.Id == userId)
        return context.Assets.Include(asset => asset.SharedWith)
            .FirstOrDefault(asset => asset.Id == id && (
                asset.IsPubliclyShared ||
                asset.SharedWith!.Any(user => user.Id == userId)
            ));
    }
    
    public MediaDto? GetOriginalData(Guid id, Guid? userId) {
        
        var media = GetAssetAsUserId(id, userId);

        if (media == null) return null;
        
        return new MediaDto {
            MimeType = media.MimeType,
            Path     = media.OriginalPath
        };
    }

    //TODO: for Thumbnails the MimeType should be the correct one (depending on which format is used for thumbnails)
    public MediaDto? GetThumbData(Guid id, Guid? userId) {
        var media = GetAssetAsUserId(id, userId);
        
        if(media == null) return null;

        if (media.ThumbnailPath == String.Empty) return null;
        
        return new MediaDto {
            MimeType = media.MimeType,
            Path     = media.ThumbnailPath
        };
    }

    //TODO: for Previews the MimeType should be the correct one (depending on which format is used for previews and if the asset is a video)
    public MediaDto? GetPreviewData(Guid id, Guid? userId) {
        var media = GetAssetAsUserId(id, userId);
        
        if(media == null) return null;
        
        if (media.PreviewPath == String.Empty) return null;
        
        return new MediaDto {
            MimeType = media.MimeType,
            Path     = media.PreviewPath
        };
    }
}