<?php

namespace App\Domains\Catalog\Models;

use App\Domains\Catalog\Enums\FeaturedGroupSource;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
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\HasMany;
use Illuminate\Support\Str;

#[Fillable([
    'tenant_code',
    'code',
    'source_type',
    'category_id',
    'product_layout',
    'group_layout',
    'group_name',
    'group_order',
])]
class FeaturedGroup extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $table = 'featured_groups';

    protected $attributes = [
        'source_type' => FeaturedGroupSource::Manual->value,
    ];

    protected static function booted(): void
    {
        static::creating(function (FeaturedGroup $featuredGroup): void {
            if (filled($featuredGroup->code)) {
                return;
            }

            $baseCode = Str::slug($featuredGroup->group_name) ?: 'group';
            $code = $baseCode;
            $suffix = 2;

            while (static::query()
                ->where('tenant_code', $featuredGroup->tenant_code)
                ->where('code', $code)
                ->exists()) {
                $code = "{$baseCode}-{$suffix}";
                $suffix++;
            }

            $featuredGroup->code = $code;
        });
    }

    protected function casts(): array
    {
        return [
            'source_type' => FeaturedGroupSource::class,
            'category_id' => 'integer',
            'product_layout' => ProductLayout::class,
            'group_layout' => GroupLayout::class,
            'group_order' => 'integer',
        ];
    }

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

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

    /** @return HasMany<FeaturedItem, $this> */
    public function featuredItems(): HasMany
    {
        return $this->hasMany(FeaturedItem::class)->orderBy('order');
    }
}
