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

namespace Baya.Application.Features.Search.Commands.RebuildSearchIndex;

internal sealed class RebuildSearchIndexCommandHandler(
    ICurrentUser currentUser,
    ISearchIndexMaintainer maintainer,
    IAuditLogger auditLogger)
    : IRequestHandler<RebuildSearchIndexCommand, OperationResult<SearchIndexRebuildResult>>
{
    public async ValueTask<OperationResult<SearchIndexRebuildResult>> Handle(RebuildSearchIndexCommand request, CancellationToken cancellationToken)
    {
        if (currentUser.UserId is not { } adminId)
            return OperationResult<SearchIndexRebuildResult>.UnauthorizedResult("Not authenticated.");

        var result = await maintainer.RebuildAsync(cancellationToken);

        await auditLogger.WriteAsync(
            "nurse_search_index",
            "rebuild",
            "rebuild",
            new Dictionary<string, object?>
            {
                ["admin_id"] = adminId,
                ["nurses_processed"] = result.NursesProcessed,
                ["rows_written"] = result.RowsWritten
            },
            cancellationToken);

        return OperationResult<SearchIndexRebuildResult>.SuccessResult(result);
    }
}
