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

namespace Indotalent.Features.Pipeline.Budget.Cqrs;

public class UpdateBudgetRequest
{
    public string? Id { get; set; }
    public string? Title { get; set; }
    public string? Description { get; set; }
    public DateTime? BudgetDate { get; set; }
    public BudgetStatus 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 UpdateBudgetResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateBudgetCommand(UpdateBudgetRequest Data) : IRequest<UpdateBudgetResponse>;

public class UpdateBudgetHandler : IRequestHandler<UpdateBudgetCommand, UpdateBudgetResponse>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return new UpdateBudgetResponse { Success = false };

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

        await _context.SaveChangesAsync(cancellationToken);

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