<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class WatchHistory extends Model
{
    protected $fillable = [
        'user_id',
        'watchable_id',
        'watchable_type',
        'duration',
        'watched_seconds',
        'completion_percentage',
        'last_watched_at'
    ];

    protected $casts = [
        'last_watched_at' => 'datetime',
    ];

    public function watchable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function movie()
    {
        return $this->belongsTo(Movie::class, 'watchable_id');
    }

    public function episode()
    {
        return $this->belongsTo(Episode::class, 'watchable_id');
    }
    public function channel()
    {
        return $this->belongsTo(LiveTv::class, 'watchable_id');
    }

    public function season()
    {
        return $this->hasOneThrough(
            Season::class,
            Episode::class,
            'id', // Foreign key on episodes table
            'id', // Foreign key on seasons table
            'watchable_id', // Local key on watch_histories table
            'season_id' // Local key on episodes table (CHANGED from series_id)
        );
    }

    public function tvshow()
    {
        return $this->hasOneThrough(
            TvShow::class,
            Episode::class,
            'id', // Foreign key on episodes table
            'id', // Foreign key on tv_shows table
            'watchable_id', // Local key on watch_histories table
            'tv_show_id' // Local key on episodes table
        );
    }
}
