using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 更新租户基本信息命令处理器。
/// </summary>
public sealed class UpdateTenantCommandHandler(ITenantRepository tenantRepository)
    : IRequestHandler<UpdateTenantCommand>
{
    /// <inheritdoc />
    public async Task Handle(UpdateTenantCommand request, CancellationToken cancellationToken)
    {
        // 1. 解析租户 ID
        if (!long.TryParse(request.TenantId, out var tenantId) || tenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "租户 ID 无效");
        }

        // 2. 获取租户（带跟踪）
        var tenant = await tenantRepository.GetByIdForUpdateAsync(tenantId, cancellationToken);
        if (tenant is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
        }

        // 3. 更新租户信息
        tenant.Name = request.Name.Trim();
        tenant.ShortName = request.ShortName?.Trim();
        tenant.LegalEntityName = request.LegalEntityName?.Trim();
        tenant.Industry = request.Industry?.Trim();
        tenant.LogoUrl = request.LogoUrl?.Trim();
        tenant.CoverImageUrl = request.CoverImageUrl?.Trim();
        tenant.Website = request.Website?.Trim();
        tenant.Country = request.Country?.Trim();
        tenant.Province = request.Province?.Trim();
        tenant.City = request.City?.Trim();
        tenant.Address = request.Address?.Trim();
        tenant.ContactName = request.ContactName?.Trim();
        tenant.ContactPhone = request.ContactPhone?.Trim();
        tenant.ContactEmail = request.ContactEmail?.Trim();
        tenant.Tags = request.Tags?.Trim();
        tenant.Remarks = request.Remarks?.Trim();

        // 4. 保存变更
        await tenantRepository.SaveChangesAsync(cancellationToken);
    }
}
