<?php

/**
 * 文件功能：异步持久化聊天记录队列
 * 承接高频聊天缓存，防堵塞 MySQL 进程。
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Jobs;

use App\Models\Message;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Carbon;

/**
 * 异步聊天消息持久化任务
 * 负责把 Redis 中的聊天消息安全写入数据库归档。
 */
class SaveMessageJob implements ShouldQueue
{
    use Queueable;

    /**
     * 创建聊天消息持久化任务。
     *
     * @param  array<string, mixed>  $messageData  包装好的消息数组
     */
    public function __construct(
        public readonly array $messageData
    ) {}

    /**
     * 执行队列任务，将已广播的聊天消息写入数据库。
     */
    public function handle(): void
    {
        Message::create([
            'room_id' => $this->messageData['room_id'],
            'from_user' => $this->messageData['from_user'],
            'to_user' => $this->messageData['to_user'] ?? '大家',
            'content' => $this->messageData['content'],
            'is_secret' => $this->messageData['is_secret'] ?? false,
            'font_color' => $this->messageData['font_color'] ?? '',
            'action' => $this->messageData['action'] ?? '',
            'message_type' => $this->messageData['message_type'] ?? 'text',
            'image_path' => $this->messageData['image_path'] ?? null,
            'image_thumb_path' => $this->messageData['image_thumb_path'] ?? null,
            'image_original_name' => $this->messageData['image_original_name'] ?? null,
            // 恢复 Carbon 时间对象
            'sent_at' => Carbon::parse($this->messageData['sent_at']),
        ]);
    }
}
