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

namespace Indotalent.Features.Pipeline.SalesRepresentative.Cqrs;

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

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

public record UpdateSalesRepresentativeCommand(UpdateSalesRepresentativeRequest Data) : IRequest<UpdateSalesRepresentativeResponse>;

public class UpdateSalesRepresentativeHandler : IRequestHandler<UpdateSalesRepresentativeCommand, UpdateSalesRepresentativeResponse>
{
    private readonly AppDbContext _context;

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

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

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

        await _context.SaveChangesAsync(cancellationToken);

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