using MediatR;
using TakeoutSaaS.Application.App.Merchants.Commands;
using TakeoutSaaS.Application.App.Merchants.Dto;
using TakeoutSaaS.Domain.Merchants.Entities;
using TakeoutSaaS.Domain.Merchants.Enums;
using TakeoutSaaS.Domain.Merchants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Merchants.Handlers;

/// <summary>
/// 更新合同状态处理器。
/// </summary>
public sealed class UpdateMerchantContractStatusCommandHandler(
    IMerchantRepository merchantRepository,
    ITenantProvider tenantProvider,
    ICurrentUserAccessor currentUserAccessor)
    : IRequestHandler<UpdateMerchantContractStatusCommand, MerchantContractDto>
{
    /// <summary>
    /// 更新合同状态。
    /// </summary>
    /// <param name="request">状态变更命令。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>合同 DTO。</returns>
    public async Task<MerchantContractDto> Handle(UpdateMerchantContractStatusCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询合同
        var tenantId = tenantProvider.GetCurrentTenantId();
        var contract = await merchantRepository.FindContractByIdAsync(request.MerchantId, tenantId, request.ContractId, cancellationToken)
                       ?? throw new BusinessException(ErrorCodes.NotFound, "合同不存在");

        // 2. 更新状态
        if (request.Status == ContractStatus.Active)
        {
            contract.Status = ContractStatus.Active;
            contract.SignedAt = request.SignedAt ?? DateTime.UtcNow;
        }
        else if (request.Status == ContractStatus.Terminated)
        {
            contract.Status = ContractStatus.Terminated;
            contract.TerminatedAt = DateTime.UtcNow;
            contract.TerminationReason = request.Reason;
        }
        else
        {
            contract.Status = request.Status;
        }

        // 3. 持久化与审计
        await merchantRepository.UpdateContractAsync(contract, cancellationToken);
        await merchantRepository.AddAuditLogAsync(new MerchantAuditLog
        {
            TenantId = tenantId,
            MerchantId = contract.MerchantId,
            Action = MerchantAuditAction.ContractStatusChanged,
            Title = $"合同状态变更为 {request.Status}",
            Description = request.Reason,
            OperatorId = ResolveOperatorId(),
            OperatorName = ResolveOperatorName()
        }, cancellationToken);

        await merchantRepository.SaveChangesAsync(cancellationToken);

        // 4. 返回 DTO
        return MerchantMapping.ToDto(contract);
    }

    private long? ResolveOperatorId()
    {
        var id = currentUserAccessor.UserId;
        return id == 0 ? null : id;
    }

    private string ResolveOperatorName()
    {
        var id = currentUserAccessor.UserId;
        return id == 0 ? "system" : $"user:{id}";
    }
}
