<?php

namespace App\Models\Fish;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Species extends Model
{
    protected $table = 'species';

    protected $fillable = [
        'slug',
        'scientific_name',
        'family',
        'tr_name',
        'en_name',
        'fishbase_id',
        'worms_aphia_id',
        'photo_url',
        'summary_md',
        'is_migratory',
        'primary_water_zone',
        'profile_status',
        'data_version',
        'updated_by',
    ];

    protected $casts = [
        'is_migratory' => 'boolean',
        'data_version' => 'integer',
    ];

    // ────── Scopes ──────

    public function scopePublished($query)
    {
        return $query->where('profile_status', 'published');
    }

    public function scopeReviewed($query)
    {
        return $query->whereIn('profile_status', ['reviewed', 'published']);
    }

    public function scopeByRegion($query, string $region)
    {
        // Bölge bazlı override'ı olan türleri filtreler
        return $query->whereHas('regionalOverrides', fn ($q) => $q->where('region_code', $region));
    }

    public function scopeMigratory($query)
    {
        return $query->where('is_migratory', true);
    }

    // ────── İlişkiler ──────

    public function featurePrefs(): HasMany
    {
        return $this->hasMany(SpeciesFeaturePref::class);
    }

    public function preyRelations(): HasMany
    {
        return $this->hasMany(SpeciesPrey::class, 'predator_id');
    }

    public function predatorRelations(): HasMany
    {
        return $this->hasMany(SpeciesPrey::class, 'prey_species_id');
    }

    public function regionalOverrides(): HasMany
    {
        return $this->hasMany(SpeciesRegionalOverride::class);
    }

    public function translations(): HasMany
    {
        return $this->hasMany(SpeciesTranslation::class);
    }

    public function revisions(): HasMany
    {
        return $this->hasMany(SpeciesRevision::class)->orderByDesc('revision_no');
    }

    public function updatedByUser(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'updated_by');
    }

    public function habitatScores(): HasMany
    {
        return $this->hasMany(StaticHabitatScore::class);
    }

    // ────── Yardımcılar ──────

    /**
     * Belirli bir bölge için efektif tercih profilini döndürür.
     * Override varsa override, yoksa global profil geçerli.
     */
    public function getEffectivePrefs(?string $regionCode = null): array
    {
        $globalPrefs = $this->featurePrefs->keyBy('feature_key');

        if (!$regionCode) {
            return $globalPrefs->toArray();
        }

        $overrides = $this->regionalOverrides
            ->where('region_code', $regionCode)
            ->keyBy('feature_key');

        $merged = $globalPrefs->toArray();
        foreach ($overrides as $key => $override) {
            $merged[$key] = $override->toArray();
        }

        return $merged;
    }

    /**
     * Profil snapshot'ı oluşturur (revizyon için).
     */
    public function createSnapshot(): array
    {
        return [
            'species' => $this->toArray(),
            'feature_prefs' => $this->featurePrefs->toArray(),
            'prey_relations' => $this->preyRelations->toArray(),
            'regional_overrides' => $this->regionalOverrides->toArray(),
        ];
    }

    /**
     * Yeni revizyon kaydeder.
     */
    public function saveRevision(string $author, string $changeNote): SpeciesRevision
    {
        $lastRevision = $this->revisions()->max('revision_no') ?? 0;

        return $this->revisions()->create([
            'revision_no' => $lastRevision + 1,
            'snapshot' => $this->createSnapshot(),
            'author' => $author,
            'change_note' => $changeNote,
        ]);
    }
}
