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

namespace Indotalent.Features.Pipeline.Budget.Cqrs;

public class CreateBudgetRequest
{
    public string? Title { get; set; }
    public string? Description { get; set; }
    public DateTime? BudgetDate { get; set; } = DateTime.Today;
    public BudgetStatus Status { get; set; } = BudgetStatus.Draft;
    public decimal? Amount { get; set; }
    public string? CampaignId { get; set; }
}

public class CreateBudgetResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
}

public record CreateBudgetCommand(CreateBudgetRequest Data) : IRequest<CreateBudgetResponse>;

public class CreateBudgetHandler : IRequestHandler<CreateBudgetCommand, CreateBudgetResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateBudgetResponse> Handle(CreateBudgetCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.Budget);
        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.Budget
        {
            AutoNumber = autoNo,
            Title = request.Data.Title,
            Description = request.Data.Description,
            BudgetDate = request.Data.BudgetDate,
            Status = request.Data.Status,
            Amount = request.Data.Amount,
            CampaignId = request.Data.CampaignId
        };

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

        return new CreateBudgetResponse { Id = entity.Id, AutoNumber = entity.AutoNumber };
    }
}