using Microsoft.EntityFrameworkCore;

namespace MktZaloService.Infrastructure.Idempotency;

/// <summary>
/// EN: Implementation of request manager for idempotency.
/// VI: Triển khai request manager cho idempotency.
/// </summary>
public class RequestManager : IRequestManager
{
    private readonly MktZaloServiceContext _context;

    public RequestManager(MktZaloServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <inheritdoc/>
    public async Task<bool> ExistAsync(Guid id)
    {
        var request = await _context
            .FindAsync<ClientRequest>(id);

        return request != null;
    }

    /// <inheritdoc/>
    public async Task CreateRequestForCommandAsync<T>(Guid id)
    {
        var exists = await ExistAsync(id);

        var request = exists
            ? throw new InvalidOperationException($"Request with {id} already exists")
            : new ClientRequest
            {
                Id = id,
                Name = typeof(T).Name,
                Time = DateTime.UtcNow
            };

        _context.Add(request);

        await _context.SaveChangesAsync();
    }
}
