<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Crew extends Model
{
    protected $fillable = [
        'name',
        'description',
        'slug',
        'image_id',
        'cover_image_id',
    ];

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

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

    protected static function booted(): void
    {
        static::creating(function (Crew $crew) {
            if (!$crew->slug) {
                $crew->slug = self::generateUniqueSlug($crew->name);
            }
        });
    }

    public static function generateUniqueSlug(?string $name): string
    {
        $base = Str::slug((string) $name);

        if ($base === '') {
            $base = self::randomAdventureSlugBase();
        }

        return self::makeUniqueSlug($base);
    }

    protected static function makeUniqueSlug(string $base): string
    {
        $slug = $base;
        $i = 2;

        while (self::where('slug', $slug)->exists()) {
            $slug = $base . '-' . $i;
            $i++;
        }

        return $slug;
    }

    protected static function randomAdventureSlugBase(): string
    {
        $adjectives = [
            'brave', 'wild', 'stormy', 'golden', 'muddy', 'curious', 'sunny', 'frosty',
            'rusty', 'proud', 'swift', 'steady', 'quiet', 'rowdy', 'tiny', 'giant',
        ];

        $nouns = [
            'otter', 'badger', 'fox', 'raven', 'wolf', 'bear', 'eagle', 'turtle',
            'trail', 'camp', 'summit', 'river', 'forest', 'torch', 'map', 'compass',
        ];

        return $adjectives[array_rand($adjectives)] . '-' . $nouns[array_rand($nouns)];
    }
}
