using Microsoft.EntityFrameworkCore;
using MktXService.Domain.AggregatesModel.TwitterAccountAggregate;
using MktXService.Domain.SeedWork;

namespace MktXService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for TwitterAccount aggregate.
/// VI: Triển khai repository cho TwitterAccount aggregate.
/// </summary>
public class TwitterAccountRepository : ITwitterAccountRepository
{
    private readonly MktXServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public TwitterAccountRepository(MktXServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public TwitterAccount Add(TwitterAccount account)
    {
        return _context.TwitterAccounts.Add(account).Entity;
    }

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

    public async Task<TwitterAccount?> GetByIdAsync(Guid id)
    {
        return await _context.TwitterAccounts
            .Include(a => a.Status)
            .FirstOrDefaultAsync(a => a.Id == id);
    }

    public async Task<TwitterAccount?> GetByTwitterUserIdAsync(string twitterUserId)
    {
        return await _context.TwitterAccounts
            .Include(a => a.Status)
            .FirstOrDefaultAsync(a => EF.Property<string>(a, "_twitterUserId") == twitterUserId);
    }

    public async Task<IEnumerable<TwitterAccount>> GetByMerchantIdAsync(Guid merchantId)
    {
        return await _context.TwitterAccounts
            .Include(a => a.Status)
            .Where(a => EF.Property<Guid>(a, "_merchantId") == merchantId)
            .OrderByDescending(a => EF.Property<DateTime>(a, "_createdAt"))
            .ToListAsync();
    }

    public async Task<IEnumerable<TwitterAccount>> GetActiveByMerchantIdAsync(Guid merchantId)
    {
        return await _context.TwitterAccounts
            .Include(a => a.Status)
            .Where(a => EF.Property<Guid>(a, "_merchantId") == merchantId 
                        && a.StatusId == TwitterAccountStatus.Active.Id)
            .ToListAsync();
    }
}
