<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Podcast extends Model
{
    use HasFactory;

    use SoftDeletes;

    protected $table = 'podcasts';

    protected $dates = ['created_at', 'updated_at', 'deleted_at', 'added_at'];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
        'added_at'   => 'datetime',
    ];

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

    public function artists()
    {
        return $this->hasManyThrough(Artist::class, Episode::class);
    }

    public function latestEpisode()
    {
        return $this->hasOne(Episode::class)
                    ->where('published', true)
                    ->orderBy('episode_number', 'desc');
    }

    public function latestArtwork()
    {
        // this follows the hasOneThrough from Episode → Artwork
        return $this->hasOneThrough(
            Artwork::class,    // final model
            Episode::class,    // intermediate
            'podcast_id',      // FK on episodes
            'id',              // PK on artworks
            'id',              // PK on podcasts
            'artwork_id'       // FK on episodes → artworks
        )
        ->where('episodes.published', true)
        ->orderBy('episodes.episode_number', 'desc');
    }


}
