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

namespace Indotalent.Features.Thirdparty.CustomerContact.Cqrs;

public class UpdateCustomerContactRequest
{
    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 string? CustomerId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateCustomerContactCommand(UpdateCustomerContactRequest Data) : IRequest<UpdateCustomerContactResponse>;

public class UpdateCustomerContactHandler : IRequestHandler<UpdateCustomerContactCommand, UpdateCustomerContactResponse>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null)
        {
            return new UpdateCustomerContactResponse { 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;
        entity.CustomerId = request.Data.CustomerId;

        await _context.SaveChangesAsync(cancellationToken);

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