<?php

namespace App\Models;

use Conner\Tagging\Taggable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Spatie\Sitemap\Contracts\Sitemapable;
use Spatie\Sitemap\Tags\Url;

class Hentai extends Model implements Sitemapable
{
    use HasFactory;
    use Taggable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'slug',
        'description',
    ];

    public function episodes()
    {
        return $this->hasMany(Episode::class, 'hentai_id');
    }

    public function title(): string
    {
        return $this->episodes->first()->title;
    }

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

    /**
     * Has a Gallery.
     */
    public function gallery()
    {
        return $this->hasMany(Gallery::class);
    }

    /**
     * Check if hentai contains loli / shota tag
     */
    public function isLoliOrShota(): bool
    {
        $problematicTags = ['Loli', 'Shota'];

        return Cache::remember(
            "episode:{$this->id}:has_problematic_tags",
            now()->addMinutes(1440),
            fn () => $this->episodes[0]->tags->pluck('name')->intersect($problematicTags)->isNotEmpty()
        );
    }

    public function toSitemapTag(): Url|string|array
    {
        return Url::create(route('hentai.index', $this->slug))
            ->setLastModificationDate(Carbon::create($this->created_at));
    }
}
