using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Targeting;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 更新公告处理器。
/// </summary>
public sealed class UpdateTenantAnnouncementCommandHandler(
    ITenantAnnouncementRepository announcementRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<UpdateTenantAnnouncementCommand, TenantAnnouncementDto?>
{
    public async Task<TenantAnnouncementDto?> Handle(UpdateTenantAnnouncementCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验租户上下文（租户端禁止跨租户）
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId <= 0)
        {
            throw new BusinessException(ErrorCodes.BadRequest, "缺少租户标识");
        }

        // 2. (空行后) 兼容旧调用：若传入 TenantId，则必须与当前租户一致
        if (request.TenantId > 0 && request.TenantId != currentTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "无权编辑其他租户公告");
        }

        // 3. (空行后) 校验输入
        if (string.IsNullOrWhiteSpace(request.Title) || string.IsNullOrWhiteSpace(request.Content))
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "公告标题和内容不能为空");
        }

        if (request.RowVersion == null || request.RowVersion.Length == 0)
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "RowVersion 不能为空");
        }
        // 3.1 (空行后) 校验目标受众类型：租户端禁止跨租户目标类型
        if (!TenantAnnouncementTargetTypePolicy.IsAllowed(request.TargetType))
        {
            throw new BusinessException(ErrorCodes.ValidationFailed, "租户端不支持该目标受众类型");
        }

        // 4. (空行后) 查询公告
        var announcement = await announcementRepository.FindByIdAsync(currentTenantId, request.AnnouncementId, cancellationToken);
        if (announcement == null)
        {
            return null;
        }

        if (announcement.Status != AnnouncementStatus.Draft)
        {
            if (announcement.Status == AnnouncementStatus.Published)
            {
                throw new BusinessException(ErrorCodes.Conflict, "已发布公告不可编辑，要编辑已发布公告，请先撤销");
            }

            throw new BusinessException(ErrorCodes.Conflict, "仅草稿公告允许编辑");
        }

        // 5. (空行后) 更新字段
        announcement.Title = request.Title.Trim();
        announcement.Content = request.Content;
        announcement.TargetType = TenantAnnouncementTargetTypePolicy.Normalize(request.TargetType);
        announcement.TargetParameters = request.TargetParameters;
        announcement.RowVersion = request.RowVersion;

        // 6. (空行后) 持久化
        try
        {
            await announcementRepository.UpdateAsync(announcement, cancellationToken);
            await announcementRepository.SaveChangesAsync(cancellationToken);
        }
        catch (Exception exception) when (exception.GetType().Name == "DbUpdateConcurrencyException")
        {
            throw new BusinessException(ErrorCodes.Conflict, "公告已被修改，请刷新后重试");
        }

        // 7. (空行后) 返回 DTO
        return announcement.ToDto(false, null);
    }
}
