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

namespace Indotalent.Features.Pipeline.Campaign.Cqrs;

public class UpdateCampaignRequest
{
    public string? Id { get; set; }
    public string? Title { get; set; }
    public string? Description { get; set; }
    public decimal? TargetRevenueAmount { get; set; }
    public DateTime? CampaignDateStart { get; set; }
    public DateTime? CampaignDateFinish { get; set; }
    public CampaignStatus Status { get; set; }
    public string? SalesTeamId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateCampaignCommand(UpdateCampaignRequest Data) : IRequest<UpdateCampaignResponse>;

public class UpdateCampaignHandler : IRequestHandler<UpdateCampaignCommand, UpdateCampaignResponse>
{
    private readonly AppDbContext _context;
    public UpdateCampaignHandler(AppDbContext context) => _context = context;

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

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

        entity.Title = request.Data.Title;
        entity.Description = request.Data.Description;
        entity.TargetRevenueAmount = request.Data.TargetRevenueAmount;
        entity.CampaignDateStart = request.Data.CampaignDateStart;
        entity.CampaignDateFinish = request.Data.CampaignDateFinish;
        entity.Status = request.Data.Status;
        entity.SalesTeamId = request.Data.SalesTeamId;

        await _context.SaveChangesAsync(cancellationToken);

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