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

namespace Indotalent.Features.Utilities.ProgramManager.Cqrs;

public class UpdateProgramManagerRequest
{
    public string? Id { get; set; }
    public string? Title { get; set; }
    public string? Summary { get; set; }
    public ProgramManagerStatus Status { get; set; }
    public ProgramManagerPriority Priority { get; set; }
    public string? ProgramManagerResourceId { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateProgramManagerCommand(UpdateProgramManagerRequest Data) : IRequest<UpdateProgramManagerResponse>;

public class UpdateProgramManagerHandler : IRequestHandler<UpdateProgramManagerCommand, UpdateProgramManagerResponse>
{
    private readonly AppDbContext _context;

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

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

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

        entity.Title = request.Data.Title;
        entity.Summary = request.Data.Summary;
        entity.Status = request.Data.Status;
        entity.Priority = request.Data.Priority;
        entity.ProgramManagerResourceId = request.Data.ProgramManagerResourceId;

        await _context.SaveChangesAsync(cancellationToken);

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