using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Infrastructure.Database;
using MediatR;
using Indotalent.Data.Enums;
using Indotalent.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Pipeline.Expense.Cqrs;

public class CreateExpenseRequest
{
    public string? Title { get; set; }
    public string? Description { get; set; }
    public DateTime? ExpenseDate { get; set; } = DateTime.Today;
    public ExpenseStatus Status { get; set; } = ExpenseStatus.Draft;
    public decimal? Amount { get; set; }
    public string? CampaignId { get; set; }
}

public class CreateExpenseResponse
{
    public string? Id { get; set; }
    public string? Code { get; set; }
}

public record CreateExpenseCommand(CreateExpenseRequest Data) : IRequest<CreateExpenseResponse>;

public class CreateExpenseHandler : IRequestHandler<CreateExpenseCommand, CreateExpenseResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateExpenseResponse> Handle(CreateExpenseCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.Expense);

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

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

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

        return new CreateExpenseResponse
        {
            Id = entity.Id,
            Code = entity.AutoNumber
        };
    }
}