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

use app\repository\BaseRepository;
use Applications\sample\modules\article\model\ArticleEventLog;

/**
 * 文章发布链路日志仓储
 * Class ArticleEventLogRepository
 * @package Applications\sample\modules\article\repository
 */
class ArticleEventLogRepository extends BaseRepository
{
    /**
     * 记录发布链路日志
     * @param array $payload
     * @return ArticleEventLog
     */
    public function create(array $payload): ArticleEventLog
    {
        return ArticleEventLog::create([
            'article_id' => (int)($payload['article_id'] ?? 0),
            'stage' => (string)($payload['stage'] ?? ''),
            'event_code' => (string)($payload['event_code'] ?? ''),
            'topic' => (string)($payload['topic'] ?? ''),
            'message' => (string)($payload['message'] ?? ''),
            'payload' => json_encode($payload['payload'] ?? [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'status' => (int)($payload['status'] ?? 1),
        ]);
    }

    /**
     * 获取文章的发布链路日志
     * @param int $articleId
     * @return array
     */
    public function listByArticleId(int $articleId): array
    {
        return ArticleEventLog::where('article_id', $articleId)
            ->order('id', 'desc')
            ->select()
            ->map(function (ArticleEventLog $log) {
                $item = $log->toArray();
                $payload = $item['payload'] ?? '';
                if (is_string($payload) && $payload !== '') {
                    $decoded = json_decode($payload, true);
                    $item['payload'] = is_array($decoded) ? $decoded : [];
                } else {
                    $item['payload'] = [];
                }
                return $item;
            })
            ->toArray();
    }
}
