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

namespace Indotalent.Features.Pipeline.SalesRepresentative.Cqrs;

public class CreateSalesRepresentativeRequest
{
    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 class CreateSalesRepresentativeResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateSalesRepresentativeCommand(CreateSalesRepresentativeRequest Data) : IRequest<CreateSalesRepresentativeResponse>;

public class CreateSalesRepresentativeHandler : IRequestHandler<CreateSalesRepresentativeCommand, CreateSalesRepresentativeResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateSalesRepresentativeResponse> Handle(CreateSalesRepresentativeCommand 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,
            Name = request.Data.Name,
            JobTitle = request.Data.JobTitle,
            EmployeeNumber = request.Data.EmployeeNumber,
            PhoneNumber = request.Data.PhoneNumber,
            EmailAddress = request.Data.EmailAddress,
            Description = request.Data.Description,
            SalesTeamId = request.Data.SalesTeamId
        };

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

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