using MediatR;
using Microsoft.EntityFrameworkCore;
using SolutionErp.Application.Common.Exceptions;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Master.Suppliers.Dtos;

namespace SolutionErp.Application.Master.Suppliers.Queries.GetSupplier;

public record GetSupplierQuery(Guid Id) : IRequest<SupplierDto>;

public class GetSupplierQueryHandler : IRequestHandler<GetSupplierQuery, SupplierDto>
{
    private readonly IApplicationDbContext _db;

    public GetSupplierQueryHandler(IApplicationDbContext db) => _db = db;

    public async Task<SupplierDto> Handle(GetSupplierQuery request, CancellationToken ct)
    {
        var x = await _db.Suppliers.AsNoTracking().FirstOrDefaultAsync(s => s.Id == request.Id, ct)
            ?? throw new NotFoundException("Supplier", request.Id);
        return new SupplierDto(x.Id, x.Code, x.Name, x.Type, x.TaxCode, x.Phone, x.Email, x.Address, x.ContactPerson, x.Note,
            x.PackageCategory, x.OfficeAddress, x.MailingAddress, x.Fax, x.BankAccount, x.SecondaryBankAccount,
            x.LegalRepresentative, x.LegalRepTitle, x.AuthorizationNote, x.LinkGuq, x.LinkGpkd, x.LinkHsnl,
            x.ContactTitle, x.ContactPhone, x.MailRecipient, x.ReferralSource, x.OwnerPmh, x.Status,
            x.SourceUpdatedAt, x.SourceUpdatedBy,
            x.CreatedAt, x.UpdatedAt, x.IsPublic);
    }
}
