using System.Data;
using Dapper;
using PlotLine.Models;

namespace PlotLine.Data;

public interface IUserFileRepository
{
    Task<long> CreateAsync(UserFile file);
    Task MarkDeletedByStoragePathAsync(string storagePath);
    Task<long> GetStorageUsageForOwnerAsync(int userId);
}

public sealed class UserFileRepository(ISqlConnectionFactory connectionFactory) : IUserFileRepository
{
    public async Task<long> CreateAsync(UserFile file)
    {
        using var connection = connectionFactory.CreateConnection();
        return await connection.QuerySingleAsync<long>(
            "dbo.UserFile_Create",
            new
            {
                file.UserID,
                file.ProjectID,
                file.EntityType,
                file.EntityID,
                file.FileName,
                file.OriginalFileName,
                file.ContentType,
                file.FileSizeBytes,
                file.StoragePath
            },
            commandType: CommandType.StoredProcedure);
    }

    public async Task MarkDeletedByStoragePathAsync(string storagePath)
    {
        using var connection = connectionFactory.CreateConnection();
        await connection.ExecuteAsync(
            "dbo.UserFile_MarkDeletedByStoragePath",
            new { StoragePath = storagePath },
            commandType: CommandType.StoredProcedure);
    }

    public async Task<long> GetStorageUsageForOwnerAsync(int userId)
    {
        using var connection = connectionFactory.CreateConnection();
        return await connection.QuerySingleAsync<long>(
            "dbo.UserFile_GetStorageUsageForOwner",
            new { UserID = userId },
            commandType: CommandType.StoredProcedure);
    }
}
