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

namespace Indotalent.Features.Pipeline.LeadActivity.Cqrs;

public class CreateLeadActivityRequest
{
    public string? LeadId { get; set; }
    public string? Summary { get; set; }
    public string? Description { get; set; }
    public DateTime? FromDate { get; set; }
    public DateTime? ToDate { get; set; }
    public Data.Enums.LeadActivityType Type { get; set; }
}

public class CreateLeadActivityResponse
{
    public string? Id { get; set; }
    public string? Summary { get; set; }
}

public record CreateLeadActivityCommand(CreateLeadActivityRequest Data) : IRequest<CreateLeadActivityResponse>;

public class CreateLeadActivityHandler : IRequestHandler<CreateLeadActivityCommand, CreateLeadActivityResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateLeadActivityResponse> Handle(CreateLeadActivityCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.LeadActivity);

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

        var entity = new Data.Entities.LeadActivity
        {
            AutoNumber = autoNo,
            LeadId = request.Data.LeadId,
            Summary = request.Data.Summary,
            Description = request.Data.Description,
            FromDate = request.Data.FromDate,
            ToDate = request.Data.ToDate,
            Type = request.Data.Type
        };

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

        return new CreateLeadActivityResponse
        {
            Id = entity.Id,
            Summary = entity.Summary
        };
    }
}