using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Infrastructure.Database;
using MediatR;

namespace Indotalent.Features.Pipeline.SalesTeam.Cqrs;

public class CreateSalesTeamRepresentativeRequest
{
    public string? SalesTeamId { 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 CreateSalesTeamRepresentativeResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateSalesTeamRepresentativeCommand(CreateSalesTeamRepresentativeRequest Data) : IRequest<CreateSalesTeamRepresentativeResponse>;

public class CreateSalesTeamRepresentativeHandler : IRequestHandler<CreateSalesTeamRepresentativeCommand, CreateSalesTeamRepresentativeResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateSalesTeamRepresentativeResponse> Handle(CreateSalesTeamRepresentativeCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.SalesRepresentative);

        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.SalesRepresentative
        {
            AutoNumber = autoNo,
            SalesTeamId = request.Data.SalesTeamId,
            Name = request.Data.Name,
            JobTitle = request.Data.JobTitle,
            EmployeeNumber = request.Data.EmployeeNumber,
            PhoneNumber = request.Data.PhoneNumber,
            EmailAddress = request.Data.EmailAddress,
            Description = request.Data.Description
        };

        _context.SalesRepresentative.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateSalesTeamRepresentativeResponse
        {
            Id = entity.Id,
            Name = entity.Name
        };
    }
}