<?php

namespace App\Http\Resources;

use App\Http\Api\ChannelApi;
use App\Http\Api\MdRender;
use App\Http\Api\UserApi;
use App\Services\AuthService;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class SentPrResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  Request  $request
     * @return array|Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        // 获取用户信息
        $user = AuthService::current($request);
        $role = 'reader';
        if ($user && $user['user_uid'] === $this->editor_uid) {
            $role = 'owner';
        }
        $channel = ChannelApi::getById($this->channel_uid);
        $mode = $request->input('mode', 'read');

        return [
            'id' => $this->id,
            'uid' => $this->uid,
            'book' => $this->book_id,
            'paragraph' => $this->paragraph,
            'word_start' => $this->word_start,
            'word_end' => $this->word_end,
            'editor' => UserApi::getByUuid($this->editor_uid),
            'channel' => $channel,
            'content' => $this->content,
            'html' => MdRender::render($this->content, [$this->channel_uid], null, $mode, $channel['type']),
            'role' => $role,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
