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

namespace Indotalent.Features.Thirdparty.Customer.Cqrs;

public class CreateCustomerContactRequest
{
    public string? CustomerId { 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 class CreateCustomerContactResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateCustomerContactCommand(CreateCustomerContactRequest Data) : IRequest<CreateCustomerContactResponse>;

public class CreateCustomerContactHandler : IRequestHandler<CreateCustomerContactCommand, CreateCustomerContactResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateCustomerContactResponse> Handle(CreateCustomerContactCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.CustomerContact);

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

        var entity = new Data.Entities.CustomerContact
        {
            AutoNumber = autoNo,
            CustomerId = request.Data.CustomerId,
            Name = request.Data.Name,
            JobTitle = request.Data.JobTitle,
            PhoneNumber = request.Data.PhoneNumber,
            EmailAddress = request.Data.EmailAddress,
            Description = request.Data.Description
        };

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

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