using Microsoft.EntityFrameworkCore;

namespace ImageBoardServerApp.Data.Repository;

public static class ImagesRepository
{
    public static async Task<List<ImageData>> getImagesAsync()
    {
        await using var db = new AppDBContext();
        return await db.Images.ToListAsync();
    }
    
    public static async Task<ImageData> getImageByIdAsync(int imageId)
    {
        await using var db = new AppDBContext();
        return await db.Images.FirstOrDefaultAsync(image => image.ImageID == imageId);
    }

    public static async Task<int> createImageAsync(ImageData imageToCreate)
    {
        await using var db = new AppDBContext();
        await db.Images.AddAsync(imageToCreate);
        if (await db.SaveChangesAsync() >= 1)
        {
            Console.WriteLine($"Created image with ID: {imageToCreate.ImageID}");
            return imageToCreate.ImageID;
        }

        return -1;
    }
    
    public static async Task<bool> updateImageAsync(ImageData imageToCreate)
    {
        await using var db = new AppDBContext();
        db.Images.Update(imageToCreate);
        return await db.SaveChangesAsync() >= 1;
    }
    
    public static async Task<bool> deleteImageAsync(int imageId)
    {
        ImageData imageToDelete = await getImageByIdAsync(imageId);
        await using var db = new AppDBContext();
        db.Remove(imageToDelete);
        return await db.SaveChangesAsync() >= 1;
    }
}