<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ImportJob extends Model
{
    // Priority sabitleri
    const PRIORITY_NEW       = 0;  // Yeni anime keşfi
    const PRIORITY_ONGOING   = 1;  // Ongoing anime güncelleme
    const PRIORITY_CROSSFILL = 2;  // Mevcut anime, eksik kaynak ekleme

    protected $fillable = [
        'source', 'source_url', 'watch_id', 'cdn_id', 'anime_title', 'anime_id',
        'animecix_title_id', 'animecix_slug',
        'season_ranges', 'status', 'priority', 'total_episodes', 'done_episodes',
        'failed_episodes', 'current_step', 'error_log',
    ];

    protected $casts = [
        'season_ranges' => 'array',
    ];

    public function anime()
    {
        return $this->belongsTo(Anime::class);
    }

    public function getProgressPercentAttribute(): int
    {
        if ($this->total_episodes === 0) return 0;
        return (int) round($this->done_episodes / $this->total_episodes * 100);
    }

    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            'pending'     => 'secondary',
            'fetching'    => 'info',
            'downloading' => 'primary',
            'uploading'   => 'warning',
            'done'        => 'success',
            'failed'      => 'danger',
            default       => 'secondary',
        };
    }

    public function getStatusLabelAttribute(): string
    {
        return match($this->status) {
            'pending'     => 'Bekliyor',
            'fetching'    => 'Bölümler Alınıyor',
            'downloading' => 'İndiriliyor',
            'uploading'   => 'Yükleniyor',
            'done'        => 'Tamamlandı',
            'failed'      => 'Hata',
            default       => $this->status,
        };
    }

    /** Toplam bölüm sayısını season_ranges'ten hesapla */
    public function buildEpisodeList(): array
    {
        if (!$this->season_ranges) return [];
        $episodes = [];
        foreach ($this->season_ranges as $range) {
            $season = (int) $range['season'];
            $from   = (int) $range['from'];
            $to     = (int) $range['to'];
            for ($ep = $from; $ep <= $to; $ep++) {
                $episodes[] = ['season' => $season, 'episode' => $ep];
            }
        }
        return $episodes;
    }

    public function getTotalFromRangesAttribute(): int
    {
        $total = 0;
        foreach (($this->season_ranges ?? []) as $r) {
            $total += max(0, (int)$r['to'] - (int)$r['from'] + 1);
        }
        return $total;
    }
}
