using Microsoft.EntityFrameworkCore;
using WhatsAppService.Domain.AggregatesModel.WhatsAppAccountAggregate;
using WhatsAppService.Domain.SeedWork;

namespace WhatsAppService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for WhatsAppAccount aggregate.
/// VI: Triển khai repository cho WhatsAppAccount aggregate.
/// </summary>
public class WhatsAppAccountRepository : IWhatsAppAccountRepository
{
    private readonly WhatsAppServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public WhatsAppAccountRepository(WhatsAppServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<WhatsAppAccount> AddAsync(WhatsAppAccount account, CancellationToken cancellationToken = default)
    {
        var entry = await _context.WhatsAppAccounts.AddAsync(account, cancellationToken);
        return entry.Entity;
    }

    public void Update(WhatsAppAccount account)
    {
        _context.Entry(account).State = EntityState.Modified;
    }

    public async Task<WhatsAppAccount?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.WhatsAppAccounts
            .Include(a => a.Status)
            .FirstOrDefaultAsync(a => a.Id == id, cancellationToken);
    }

    public async Task<WhatsAppAccount?> GetByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.WhatsAppAccounts
            .Include(a => a.Status)
            .FirstOrDefaultAsync(a => EF.Property<Guid>(a, "_shopId") == shopId, cancellationToken);
    }

    public async Task<WhatsAppAccount?> GetByPhoneNumberIdAsync(string phoneNumberId, CancellationToken cancellationToken = default)
    {
        return await _context.WhatsAppAccounts
            .Include(a => a.Status)
            .FirstOrDefaultAsync(a => EF.Property<string>(a, "_phoneNumberId") == phoneNumberId, cancellationToken);
    }
}
