using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Enums;
using TakeoutSaaS.Domain.Stores.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Stores.Handlers;

/// <summary>
/// 更新门店资质处理器。
/// </summary>
public sealed class UpdateStoreQualificationCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<UpdateStoreQualificationCommandHandler> logger)
    : IRequestHandler<UpdateStoreQualificationCommand, StoreQualificationDto?>
{
    /// <inheritdoc />
    public async Task<StoreQualificationDto?> Handle(UpdateStoreQualificationCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验门店存在
        var tenantId = tenantProvider.GetCurrentTenantId();
        var store = await storeRepository.FindByIdAsync(request.StoreId, tenantId, cancellationToken);
        if (store is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "门店不存在");
        }

        // 2. (空行后) 审核中门店禁止修改资质
        if (store.AuditStatus == StoreAuditStatus.Pending)
        {
            throw new BusinessException(ErrorCodes.Conflict, "门店审核中，无法修改资质");
        }

        // 3. (空行后) 校验资质记录
        var qualification = await storeRepository.FindQualificationByIdAsync(request.QualificationId, tenantId, cancellationToken);
        if (qualification is null || qualification.StoreId != request.StoreId)
        {
            return null;
        }

        // 4. (空行后) 更新字段
        if (!string.IsNullOrWhiteSpace(request.FileUrl))
        {
            qualification.FileUrl = request.FileUrl.Trim();
        }

        if (request.DocumentNumber is not null)
        {
            qualification.DocumentNumber = request.DocumentNumber.Trim();
        }

        if (request.IssuedAt.HasValue)
        {
            qualification.IssuedAt = request.IssuedAt;
        }

        if (request.ExpiresAt.HasValue)
        {
            qualification.ExpiresAt = request.ExpiresAt;
        }

        if (request.SortOrder.HasValue)
        {
            qualification.SortOrder = request.SortOrder.Value;
        }

        // 5. (空行后) 保存变更并返回结果
        await storeRepository.UpdateQualificationAsync(qualification, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("更新门店资质 {QualificationId} 对应门店 {StoreId}", qualification.Id, request.StoreId);

        return StoreMapping.ToDto(qualification);
    }
}
