<?php

namespace App\Models;

use App\Traits\HasSlugHistory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Operator extends Model
{
    use HasFactory, HasSlugHistory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'name',
        'slug',
        'website',
        'headquarters',
        'description',
        'total_parks',
        'total_rides',
    ];

    /**
     * Get the parks operated by this company.
     */
    public function parks(): HasMany
    {
        return $this->hasMany(Park::class);
    }

    /**
     * Update park statistics.
     */
    public function updateStatistics(): void
    {
        $this->total_parks = $this->parks()->count();
        $this->total_rides = $this->parks()->sum('ride_count');
        $this->save();
    }

    /**
     * Get the operator's name with total parks.
     */
    public function getDisplayNameAttribute(): string
    {
        return "{$this->name} ({$this->total_parks} parks)";
    }

    /**
     * Get formatted website URL (ensures proper URL format).
     */
    public function getWebsiteUrlAttribute(): string
    {
        if (!$this->website) {
            return '';
        }

        $website = $this->website;
        if (!str_starts_with($website, 'http://') && !str_starts_with($website, 'https://')) {
            $website = 'https://' . $website;
        }

        return $website;
    }

    /**
     * Scope a query to only include major operators (with multiple parks).
     */
    public function scopeMajorOperators($query, int $minParks = 3)
    {
        return $query->where('total_parks', '>=', $minParks);
    }

    /**
     * Get the route key for the model.
     */
    public function getRouteKeyName(): string
    {
        return 'slug';
    }
}