using CashLineERP.Application.Identity;
using CashLineERP.Domain.Identity;
using Microsoft.EntityFrameworkCore;

namespace CashLineERP.Infrastructure.Persistence.Repositories;

public sealed class AccountingOfficeClientRequestRepository : IAccountingOfficeClientRequestRepository
{
    private readonly CashLineErpDbContext _dbContext;

    public AccountingOfficeClientRequestRepository(CashLineErpDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IReadOnlyCollection<AccountingOfficeClientRequest> GetClientRequests(long clientPartyId) =>
        _dbContext.AccountingOfficeClientRequests
            .AsNoTracking()
            .Where(entry => entry.ClientPartyId == clientPartyId)
            .OrderByDescending(entry => entry.CreatedAtUtc)
            .ThenByDescending(entry => entry.Id)
            .ToArray();

    public IReadOnlyCollection<AccountingOfficeClientRequest> GetAssignedClientRequests(long accountingOfficeUserId, long clientPartyId) =>
        _dbContext.AccountingOfficeClientRequests
            .AsNoTracking()
            .Where(entry => entry.ClientPartyId == clientPartyId)
            .Where(entry => entry.AssignedAccountingOfficeUserId == accountingOfficeUserId)
            .OrderByDescending(entry => entry.CreatedAtUtc)
            .ThenByDescending(entry => entry.Id)
            .ToArray();

    public AccountingOfficeClientRequest? GetClientRequest(long requestId) =>
        _dbContext.AccountingOfficeClientRequests.SingleOrDefault(entry => entry.Id == requestId);

    public AccountingOfficeClientRequest Create(AccountingOfficeClientRequest request)
    {
        _dbContext.AccountingOfficeClientRequests.Add(request);
        _dbContext.SaveChanges();
        return request;
    }

    public AccountingOfficeClientRequest Update(AccountingOfficeClientRequest request)
    {
        _dbContext.SaveChanges();
        return request;
    }
}

