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

namespace Indotalent.Features.Thirdparty.Vendor.Cqrs;

public class CreateVendorContactRequest
{
    public string? VendorId { 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 CreateVendorContactResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateVendorContactCommand(CreateVendorContactRequest Data) : IRequest<CreateVendorContactResponse>;

public class CreateVendorContactHandler : IRequestHandler<CreateVendorContactCommand, CreateVendorContactResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateVendorContactResponse> Handle(CreateVendorContactCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.VendorContact);

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

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

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

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