<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace Applications\sample\modules\article\queue;

use Core\service\queue\contract\QueueHandlerInterface;
use Applications\sample\modules\article\repository\ArticleEventLogRepository;

/**
 * Article Published Handler
 * @package Applications\sample\modules\article\queue
 */
class ArticlePublishedHandler implements QueueHandlerInterface
{
    /**
     * 获取队列主题名称
     * @return string
     */
    public function topic(): string
    {
        return 'sample.article.published';
    }


    /**
     * 处理文章发布事件
     * @param array $payload 事件载荷数据
     * @return void
     */
    public function handle(array $payload): void
    {
        $articleId = (int)($payload['article_id'] ?? 0);
        $title = (string)($payload['title'] ?? '');
        $triggerTime = (string)($payload['trigger_time'] ?? date('Y-m-d H:i:s'));

        app()->make(ArticleEventLogRepository::class)->create([
            'article_id' => $articleId,
            'stage' => 'queue_handle',
            'event_code' => 'Applications\sample\modules\article\event\ArticlePublished',
            'topic' => $this->topic(),
            'message' => sprintf('异步处理完成：已为《%s》生成发布后续任务记录', $title),
            'payload' => [
                'article_id' => $articleId,
                'title' => $title,
                'trigger_time' => $triggerTime,
                'handled_time' => date('Y-m-d H:i:s'),
            ],
            'status' => 1,
        ]);
    }
}
