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

use Core\service\BaseCoreService;
use Applications\sample\modules\article\event\ArticlePublished;
use Applications\sample\modules\article\repository\ArticleRepository;
use think\facade\Log;

/**
 * Core Article Service
 * @package Applications\sample\modules\article\core
 */
class CoreArticleService extends BaseCoreService
{
    /**
     * 创建文章
     */
    public function create(array $payload): array
    {
        $title = trim((string)($payload['title'] ?? ''));
        if ($title === '') {
            return ['code' => 1, 'msg' => '标题不能为空'];
        }

        $data = [
            'title' => $title,
            'category_id' => (int)($payload['category_id'] ?? 0),
            'cover_image' => (string)($payload['cover_image'] ?? ''),
            'content' => (string)($payload['content'] ?? ''),
            'audio_url' => (string)($payload['audio_url'] ?? ''),
            'source_url' => (string)($payload['source_url'] ?? ''),
            'price' => round((float)($payload['price'] ?? 0), 2),
            'status' => (int)($payload['status'] ?? 1) ? 1 : 0,
        ];

        $article = $this->repository()->create($data);
        $id = $article->id;

        // 发布时投递队列
        if ($data['status'] === 1) {
            $this->dispatchPublished((int)$id, $title);
        }

        return ['code' => 0, 'msg' => '创建成功', 'data' => ['id' => $id]];
    }

    /**
     * 更新文章
     */
    public function update(int $id, array $payload): array
    {
        $article = $this->repository()->findById($id);
        if (!$article) {
            return ['code' => 1, 'msg' => '文章不存在'];
        }

        $title = trim((string)($payload['title'] ?? ''));
        if ($title === '') {
            return ['code' => 1, 'msg' => '标题不能为空'];
        }

        $data = [
            'title' => $title,
            'category_id' => (int)($payload['category_id'] ?? $article->category_id),
            'cover_image' => (string)($payload['cover_image'] ?? $article->cover_image),
            'content' => (string)($payload['content'] ?? $article->content),
            'audio_url' => (string)($payload['audio_url'] ?? $article->audio_url),
            'source_url' => (string)($payload['source_url'] ?? $article->source_url),
            'price' => round((float)($payload['price'] ?? 0), 2),
            'status' => (int)($payload['status'] ?? 1) ? 1 : 0,
        ];

        $previousStatus = (int)$article->status;
        $this->repository()->save($article, $data);

        // 新发布时投递队列
        if ($data['status'] === 1 && $previousStatus !== 1) {
            $this->dispatchPublished($id, $title);
        }

        return ['code' => 0, 'msg' => '更新成功', 'data' => ['id' => $id]];
    }

    /**
     * 删除文章（软删为下架）
     */
    public function delete(int $id): array
    {
        if ($id <= 0) {
            return ['code' => 1, 'msg' => '参数错误'];
        }
        if (!$this->repository()->exists($id)) {
            return ['code' => 1, 'msg' => '文章不存在'];
        }

        $this->repository()->deleteById($id);
        return ['code' => 0, 'msg' => '删除成功'];
    }

    /**
     * 投递文章发布事件
     * @param int $id 文章ID
     * @param string $title 文章标题
     * @return void
     */
    private function dispatchPublished(int $id, string $title): void
    {
        try {
            $this->app->event->trigger(new ArticlePublished($id, $title, date('Y-m-d H:i:s')));
        } catch (\Throwable $e) {
            Log::error('sample article publish event trigger failed: ' . $e->getMessage(), [
                'article_id' => $id,
                'title' => $title,
            ]);
            // 事件或队列不可用不影响主流程
        }
    }

    /**
     * 获取文章仓库实例
     * @return ArticleRepository
     */
    private function repository(): ArticleRepository
    {
        return $this->app->make(ArticleRepository::class);
    }
}
