using MediatR;
using IamService.Domain.AggregatesModel.OrganizationAggregate;
using IamService.Domain.Exceptions;

namespace IamService.API.Application.Commands.Organizations;

/// <summary>
/// EN: Handler for UpdateOrganizationCommand.
/// VI: Handler cho UpdateOrganizationCommand.
/// </summary>
public class UpdateOrganizationCommandHandler : IRequestHandler<UpdateOrganizationCommand, UpdateOrganizationCommandResult>
{
    private readonly IOrganizationRepository _organizationRepository;
    private readonly ILogger<UpdateOrganizationCommandHandler> _logger;

    public UpdateOrganizationCommandHandler(
        IOrganizationRepository organizationRepository,
        ILogger<UpdateOrganizationCommandHandler> logger)
    {
        _organizationRepository = organizationRepository;
        _logger = logger;
    }

    public async Task<UpdateOrganizationCommandResult> Handle(
        UpdateOrganizationCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Updating organization: {Id}", request.Id);

        var organization = await _organizationRepository.GetByIdAsync(request.Id, cancellationToken);

        if (organization == null)
        {
            throw new DomainException($"Organization with ID '{request.Id}' not found.");
        }

        organization.UpdateInfo(request.Name, request.Description);

        _organizationRepository.Update(organization);

        await _organizationRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("Organization {Id} updated successfully", request.Id);

        return new UpdateOrganizationCommandResult(
            organization.Id,
            organization.Name,
            organization.Description,
            organization.UpdatedAt);
    }
}
