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

namespace Indotalent.Features.Pipeline.LeadActivity.Cqrs;

public class UpdateLeadActivityRequest
{
    public string? Id { get; set; }
    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 DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateLeadActivityCommand(UpdateLeadActivityRequest Data) : IRequest<UpdateLeadActivityResponse>;

public class UpdateLeadActivityHandler : IRequestHandler<UpdateLeadActivityCommand, UpdateLeadActivityResponse>
{
    private readonly AppDbContext _context;

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

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

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

        entity.LeadId = request.Data.LeadId;
        entity.Summary = request.Data.Summary;
        entity.Description = request.Data.Description;
        entity.FromDate = request.Data.FromDate;
        entity.ToDate = request.Data.ToDate;
        entity.Type = request.Data.Type;

        await _context.SaveChangesAsync(cancellationToken);

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