<?php

namespace App\Services;

use App\Http\Traits\CommonTrait;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Collection;
use App\Models\Post;
use App\Models\PostTag;
use App\Models\DTO\SearchData;

class TagService
{
    use CommonTrait;

    public Post $postModel;
    public PostTag $postTagModel;

	public function __construct(Post $postModel, PostTag $postTagModel)
    {
		$this->postModel = $postModel;
		$this->postTagModel = $postTagModel;
	}

    // 모든 태그 조회
    public function getAllTags(): Collection
    {
        $cacheName = 'tags';
        if (!$result = Cache::get($cacheName)) {
            $result = $this->postTagModel->getAllTags();

            if ($result) {
                Cache::put($cacheName, $result, now()->addMonths(6));
            }
        }

        return $result;
    }

    // 태그로 관련 게시글 조회
    public function getPostsByTag(SearchData $params): object
    {
        $data = $this->postTagModel->getPostsByTag($params);

        if ($data && $data->total > 0) {
            foreach ($data->list as $item) {
                $item->content = $this->strCut(preg_replace('/<img[^>]*>/i', '', $item->content), 300);
                $item->createdAt = date('Y.m.d H:i:s', strtotime($item->created_at));
                $item->tags = array_map('trim', explode(',', $item->tags));
            }
        }

        return $data;
    }
}
