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

namespace Indotalent.Features.Pipeline.SalesTeam.Cqrs;

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

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

public record UpdateSalesTeamRepresentativeCommand(UpdateSalesTeamRepresentativeRequest Data) : IRequest<UpdateSalesTeamRepresentativeResponse>;

public class UpdateSalesTeamRepresentativeHandler : IRequestHandler<UpdateSalesTeamRepresentativeCommand, UpdateSalesTeamRepresentativeResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

        await _context.SaveChangesAsync(cancellationToken);

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