<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Spatie\Feed\Feedable;
use Spatie\Feed\FeedItem;

/**
 * Class RssPost
 *
 * @property int $id
 * @property int|null $category_id
 * @property string $source
 * @property string $source_url
 * @property string $post_url
 * @property string $title
 * @property string $slug
 * @property string|null $body
 * @property string|null $keywords
 * @property string|null $entities
 * @property string|null $metadata
 * @property string|null $bites
 * @property string|null $keyword_list
 * @property bool $keyword_saved
 * @property string|null $impact
 * @property string $impact_level
 * @property Carbon $published_at
 * @property string $status
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property Category|null $category
 */
class RssPost extends Model implements Feedable
{
    protected $table = 'rss_posts';

    protected $casts = [
        'category_id' => 'int',
        'published_at' => 'datetime',
        'metadata' => 'object',
        'keywords' => 'array',
        'entities' => 'array',
        'keyword_saved' => 'boolean',
    ];

    protected $fillable = [
        'category_id',
        'source',
        'source_url',
        'post_url',
        'post_domain',
        'title',
        'slug',
        'body',
        'keywords',
        'entities',
        'metadata',
        'bites',
        'keyword_list',
        'impact',
        'impact_level',
        'published_at',
        'status',
        'keyword_saved',
    ];

    public function entities_keywords()
    {
        return $this->hasMany(RssPostKeyword::class);
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function getAllKeywordsAttribute()
    {
        if (! is_empty($this->keyword_list)) {
            return array_unique(explode(',', $this->keyword_list));
        }

        return [];

    }

    public function toFeedItem(): FeedItem
    {
        return FeedItem::create([
            'id' => $this->id,
            'title' => $this->title,
            'summary' => $this->bites,
            'updated' => $this->published_at,
            // 'link' => route('front.post', ['slug' => $this->slug, 'category_slug' => $this->category->slug]),
            'authorName' => 'FutureWalker',
        ]);
    }

    public static function getFeedItems()
    {
        return self::with('category')->where('status', 'published')->latest('published_at')->take(60)->get();
    }
}
