<?php

namespace App\Domains\Catalog\Models;

use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[Fillable([
    'tenant_code',
    'categoria_id',
    'nombre',
    'is_enabled',
])]
class Category extends Model
{
    use HasFactory;

    protected $table = 'categorias';

    protected $attributes = [
        'is_enabled' => true,
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'categoria_id' => 'integer',
            'is_enabled' => 'boolean',
        ];
    }

    public function isGlobal(): bool
    {
        return $this->tenant_code === null;
    }

    /**
     * @return BelongsTo<Tenant, $this>
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class, 'tenant_code', 'codigo');
    }

    /**
     * @return BelongsTo<Category, $this>
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(self::class, 'categoria_id');
    }

    /**
     * @return HasMany<Category, $this>
     */
    public function subCategories(): HasMany
    {
        return $this->hasMany(self::class, 'categoria_id');
    }

    /** @return HasMany<CatalogItem, $this> */
    public function catalogItems(): HasMany
    {
        return $this->hasMany(CatalogItem::class);
    }

    /** @return BelongsToMany<User, $this> */
    public function scanners(): BelongsToMany
    {
        return $this->belongsToMany(
            User::class,
            'category_scanners',
            'categoria_id',
            'user_id',
        )->withTimestamps();
    }
}
