using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
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 DeleteStoreQualificationCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<DeleteStoreQualificationCommandHandler> logger)
    : IRequestHandler<DeleteStoreQualificationCommand, bool>
{
    /// <inheritdoc />
    public async Task<bool> Handle(DeleteStoreQualificationCommand 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 false;
        }

        // 4. (空行后) 已激活的外部门店必须保留必要资质
        if (store.OwnershipType == StoreOwnershipType.DifferentEntity
            && store.AuditStatus == StoreAuditStatus.Activated
            && IsLicenseType(qualification.QualificationType))
        {
            var qualifications = await storeRepository.GetQualificationsAsync(request.StoreId, tenantId, cancellationToken);
            var remainingValid = qualifications
                .Where(item => IsLicenseType(item.QualificationType))
                .Where(item => item.Id != qualification.Id && !item.IsExpired)
                .ToList();

            if (remainingValid.Count == 0)
            {
                throw new BusinessException(ErrorCodes.Forbidden, "不能删除必要资质");
            }
        }

        // 5. (空行后) 执行删除
        await storeRepository.DeleteQualificationAsync(request.QualificationId, tenantId, cancellationToken);
        await storeRepository.SaveChangesAsync(cancellationToken);
        logger.LogInformation("删除门店资质 {QualificationId} 对应门店 {StoreId}", qualification.Id, request.StoreId);

        return true;
    }

    private static bool IsLicenseType(StoreQualificationType type)
        => type is StoreQualificationType.BusinessLicense or StoreQualificationType.FoodServiceLicense;
}
