using Microsoft.AspNetCore.SignalR;

namespace Health.WebApi.Hubs;

/// <summary>
/// 问诊实时通信 Hub（开发阶段跳过认证）
/// 消息同时持久化到 DB + 广播到组
/// </summary>
public sealed class ConsultationHub : Hub
{
    private readonly IServiceProvider _sp;

    public ConsultationHub(IServiceProvider sp) => _sp = sp;

    public async Task JoinConsultation(string consultationId)
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, consultationId);
    }

    public async Task LeaveConsultation(string consultationId)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, consultationId);
    }

    /// <summary>
    /// 发送消息：先存 DB，再广播给组内其他人（不发给自己避免重复）
    /// 返回服务器端消息详情（含真实 ID）
    /// </summary>
    public async Task<object> SendMessage(string consultationId, string senderType, string? senderName, string content)
    {
        var msgId = Guid.NewGuid();
        var createdAt = DateTime.UtcNow;

        // 持久化到数据库
        using var scope = _sp.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var msg = new ConsultationMessage
        {
            Id = msgId,
            ConsultationId = Guid.Parse(consultationId),
            SenderType = Enum.Parse<ConsultationSenderType>(senderType),
            SenderName = senderName,
            Content = content,
            CreatedAt = createdAt
        };
        db.ConsultationMessages.Add(msg);

        // 更新问诊状态（如果用户发了消息，说明 AI 阶段结束）
        var consultation = await db.Consultations.FirstOrDefaultAsync(c => c.Id == msg.ConsultationId);
        if (consultation != null && consultation.Status == ConsultationStatus.AiTalking)
        {
            consultation.Status = ConsultationStatus.WaitingDoctor;
        }

        await db.SaveChangesAsync();

        // 广播给组内其他人（不包括发送者，避免客户端重复显示）
        await Clients.OthersInGroup(consultationId).SendAsync("ReceiveMessage", new
        {
            id = msgId,
            consultationId,
            senderType,
            senderName,
            content,
            createdAt
        });

        // 返回服务器消息详情给调用者（用于更新本地 ID）
        return new { id = msgId, consultationId, senderType, senderName, content, createdAt };
    }
}
