<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TvShow extends Model
{
    protected $fillable = [
        'title',
        'slug',
        'seo_title',
        'description',
        'stars',
        'director',
        'writer',
        'rating',
        'release',
        'country',
        'genre',
        'language',
        'video_type',
        'runtime',
        'video_quality',
        'is_free',
        'is_featured',
        'is_original',
        'is_blockbuster',
        'is_real_life_story',
        'status',
        'trailer',
        'trailler_youtube_source',
        'enable_download',
        'focus_keyword',
        'meta_description',
        'tags',
        'imdb_rating',
        'is_tvseries',
        'total_rating',
        'today_view',
        'weekly_view',
        'monthly_view',
        'total_view',
        'last_ep_added',
        'imdbid',
        'thumbnail',
        'poster',
        'tmdb_id',
        'is_recommended',
        'is_popular',
        'rental_duration',
        'rental_price',
        'rental_type',
        'is_rental',
        'is_free',
    ];

    /**
     * IMDB-style score: one decimal, clamped 0.0–10.0 (matches DB string length).
     */
    public static function normalizeImdbRating(mixed $value): ?string
    {
        if ($value === null || $value === '') {
            return null;
        }
        if (is_string($value)) {
            $value = trim($value);
            if ($value === '') {
                return null;
            }
        }
        if (! is_numeric($value)) {
            return null;
        }
        $n = min(10.0, max(0.0, round((float) $value, 1)));

        return number_format($n, 1, '.', '');
    }

    public function setImdbRatingAttribute($value): void
    {
        $this->attributes['imdb_rating'] = static::normalizeImdbRating($value);
    }

    public function quality()
    {
        return $this->belongsTo(VideoQuality::class, 'video_quality', 'id');
    }

    public function type()
    {
        return $this->belongsTo(Category::class, 'video_type', 'id');
    }

    public function getRelatedSeasonsAttribute()
    {
        return Season::whereJsonContains('tv_show_id', $this->id)
            ->orderBy('order')
            ->get();
    }

    public function seasons()
    {
        return Season::whereJsonContains('tv_show_id', (string) $this->id)
            ->orderBy('order');
    }

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

    public function favoritedByUsers()
    {
        return $this->belongsToMany(User::class, 'favorite_tv_shows');
    }

    public function reviews()
    {
        return $this->morphMany(Review::class, 'reviewable');
    }

    public function isFavoritedByLoggedInUser()
    {
        return $this->favoritedByUsers->contains(auth()->id());
    }
}
