#nullable enable
using Baya.Application.Common;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Mediator;

namespace Baya.Application.Features.PartnerCenters.Commands.SponsorNurse;

/// <summary>
/// Sets (or clears) the nurse's sponsoring center. Authorization: staff, or the center's own dashboard account
/// (a center may sponsor within itself). A link points <c>nurse_profiles.partner_center_id</c> at the center;
/// unlinking sets it back to <c>null</c> (once Balinyaar holds its own permit).
/// </summary>
internal sealed class SponsorNurseCommandHandler(
    ICurrentUser currentUser,
    IUnitOfWork unitOfWork)
    : IRequestHandler<SponsorNurseCommand, OperationResult<bool>>
{
    public async ValueTask<OperationResult<bool>> Handle(SponsorNurseCommand request, CancellationToken cancellationToken)
    {
        if (currentUser.UserId is not { } userId)
            return OperationResult<bool>.UnauthorizedResult("Not authenticated.");

        var centerAdminUserId = await unitOfWork.PartnerCenterRepository.GetAdminUserIdAsync(request.CenterId, cancellationToken);
        if (centerAdminUserId is null)
            return OperationResult<bool>.NotFoundResult("Partner center not found.");

        if (!StaffRoles.IsStaff(currentUser.Roles) && centerAdminUserId != userId)
            return OperationResult<bool>.ForbiddenResult("Only staff or the center's own account can sponsor nurses here.");

        var nurse = await unitOfWork.NurseProfileRepository.GetTrackedByIdAsync(request.NurseProfileId, cancellationToken);
        if (nurse is null)
            return OperationResult<bool>.NotFoundResult("Nurse profile not found.");

        nurse.PartnerCenterId = request.Unlink ? null : request.CenterId;
        await unitOfWork.CommitAsync();

        return OperationResult<bool>.SuccessResult(true);
    }
}
