using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Thirdparty.Vendor.Cqrs;

public class UpdateVendorContactRequest
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? JobTitle { get; set; }
    public string? PhoneNumber { get; set; }
    public string? EmailAddress { get; set; }
    public string? Description { get; set; }
}

public class UpdateVendorContactResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateVendorContactCommand(UpdateVendorContactRequest Data) : IRequest<UpdateVendorContactResponse>;

public class UpdateVendorContactHandler : IRequestHandler<UpdateVendorContactCommand, UpdateVendorContactResponse>
{
    private readonly AppDbContext _context;

    public UpdateVendorContactHandler(AppDbContext context) => _context = context;

    public async Task<UpdateVendorContactResponse> Handle(UpdateVendorContactCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.VendorContact
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null)
        {
            return new UpdateVendorContactResponse
            {
                Id = request.Data.Id,
                Success = false
            };
        }

        entity.Name = request.Data.Name;
        entity.JobTitle = request.Data.JobTitle;
        entity.PhoneNumber = request.Data.PhoneNumber;
        entity.EmailAddress = request.Data.EmailAddress;
        entity.Description = request.Data.Description;

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateVendorContactResponse
        {
            Id = entity.Id,
            Success = true
        };
    }
}