using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Stores.Commands;
using TakeoutSaaS.Application.App.Stores.Dto;
using TakeoutSaaS.Domain.Stores.Entities;
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 CreateStoreQualificationCommandHandler(
    IStoreRepository storeRepository,
    ITenantProvider tenantProvider,
    ILogger<CreateStoreQualificationCommandHandler> logger)
    : IRequestHandler<CreateStoreQualificationCommand, StoreQualificationDto>
{
    /// <inheritdoc />
    public async Task<StoreQualificationDto> Handle(CreateStoreQualificationCommand 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 qualifications = await storeRepository.GetQualificationsAsync(request.StoreId, tenantId, cancellationToken);
        var shouldReplace = ShouldReplace(request.QualificationType);
        var existing = shouldReplace
            ? qualifications.FirstOrDefault(x => x.QualificationType == request.QualificationType)
            : null;

        // 4. (空行后) 构建或更新资质实体
        if (existing is null)
        {
            existing = new StoreQualification
            {
                StoreId = request.StoreId,
                QualificationType = request.QualificationType,
                FileUrl = request.FileUrl.Trim(),
                DocumentNumber = request.DocumentNumber?.Trim(),
                IssuedAt = request.IssuedAt,
                ExpiresAt = request.ExpiresAt,
                SortOrder = request.SortOrder
            };

            await storeRepository.AddQualificationAsync(existing, cancellationToken);
        }
        else
        {
            existing.FileUrl = request.FileUrl.Trim();
            existing.DocumentNumber = request.DocumentNumber?.Trim();
            existing.IssuedAt = request.IssuedAt;
            existing.ExpiresAt = request.ExpiresAt;
            existing.SortOrder = request.SortOrder;

            await storeRepository.UpdateQualificationAsync(existing, cancellationToken);
        }

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

        return StoreMapping.ToDto(existing);
    }

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