<?php

namespace App\Models;

use App\Models\Reel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Str;

class Shop extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'logo',
        'brand_color',
        'contact',
        'created_by',
    ];

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

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

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

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

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

        $slug = $base;
        $counter = 1;

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

        return $slug;
    }

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

    public function getRouteKey()
    {
        return $this->getAttribute($this->getRouteKeyName()) ?: $this->getKey();
    }

    public function resolveRouteBinding($value, $field = null)
    {
        $query = $this->newQuery();

        if ($field !== null) {
            return $query->where($field, $value)->first();
        }

        $model = $query->where($this->getRouteKeyName(), $value)->first();
        if ($model) {
            return $model;
        }

        if (is_numeric($value)) {
            $model = $this->newQuery()->whereKey((int) $value)->first();
            if ($model) {
                return $model;
            }
        }

        throw (new ModelNotFoundException())->setModel(static::class, [$value]);
    }

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

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

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

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