<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;

class FoodCart extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'logo',
        'description',
        'delivery_links',
        'is_active',
        'created_by',
    ];

    protected $casts = [
        'delivery_links' => 'array',
        'is_active' => 'boolean',
    ];

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function (self $foodCart) {
            if (! $foodCart->slug) {
                $foodCart->slug = static::generateUniqueSlug((string) $foodCart->name);
            }
        });

        static::updating(function (self $foodCart) {
            if ($foodCart->isDirty('name') && ! $foodCart->isDirty('slug')) {
                $foodCart->slug = static::generateUniqueSlug((string) $foodCart->name, (int) $foodCart->id);
            }
        });
    }

    protected static function generateUniqueSlug(string $name, ?int $ignoreId = null): string
    {
        $base = Str::slug($name);
        if ($base === '') {
            $base = 'food-cart';
        }

        $slug = $base;
        $counter = 1;

        while (static::query()
            ->when($ignoreId, fn(Builder $query) => $query->where('id', '!=', $ignoreId))
            ->where('slug', $slug)
            ->exists()
        ) {
            $slug = $base . '-' . $counter;
            $counter++;
        }

        return $slug;
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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