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

namespace Indotalent.Features.Pipeline.Expense.Cqrs;

public class UpdateExpenseRequest
{
    public string? Id { get; set; }
    public string? Title { get; set; }
    public string? Description { get; set; }
    public DateTime? ExpenseDate { get; set; }
    public ExpenseStatus Status { get; set; }
    public decimal? Amount { get; set; }
    public string? CampaignId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public class UpdateExpenseResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateExpenseCommand(UpdateExpenseRequest Data) : IRequest<UpdateExpenseResponse>;

public class UpdateExpenseHandler : IRequestHandler<UpdateExpenseCommand, UpdateExpenseResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<UpdateExpenseResponse> Handle(UpdateExpenseCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Expense
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null)
        {
            return new UpdateExpenseResponse { Id = request.Data.Id, Success = false };
        }

        entity.Title = request.Data.Title;
        entity.Description = request.Data.Description;
        entity.ExpenseDate = request.Data.ExpenseDate;
        entity.Status = request.Data.Status;
        entity.Amount = request.Data.Amount;
        entity.CampaignId = request.Data.CampaignId;

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateExpenseResponse
        {
            Id = entity.Id,
            Success = true
        };
    }
}