<?php

declare(strict_types=1);

namespace App\Domain\Blog;

use App\Models\Article;
use Illuminate\Support\Str;

class ArticleExcerpt
{
    public function __construct(
        protected ArticleAccess $access,
    ) {}

    /**
     * Safe list/card excerpt — never render full body for restricted articles.
     */
    public function forList(Article $article, int $limit = 160): string
    {
        if (filled($article->description)) {
            return Str::limit((string) $article->description, $limit);
        }

        $decision = $this->access->resolve($article, null, []);
        if (! $decision->isAllow()) {
            $html = $this->access->publicHtml($article, $decision);

            return Str::limit(trim(html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8')), $limit);
        }

        return Str::limit(trim(strip_tags($article->renderedHtml())), $limit);
    }
}
