<?php

namespace App\Models;

use App\Concerns\RecordsCreator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use OwenIt\Auditing\Auditable as AuditableTrait;
use OwenIt\Auditing\Contracts\Auditable;

class FactoryUnit extends Model implements Auditable
{
    use AuditableTrait, RecordsCreator;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'is_active',
    ];

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

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

    /**
     * @return list<array{id: int, name: string, is_active: bool}>
     */
    public static function optionsForForm(?int $currentUnitId = null): array
    {
        return self::query()
            ->when(
                $currentUnitId,
                fn ($query) => $query->where(function ($q) use ($currentUnitId): void {
                    $q->where('is_active', true)
                        ->orWhere('id', $currentUnitId);
                }),
                fn ($query) => $query->where('is_active', true),
            )
            ->orderBy('name')
            ->get(['id', 'name', 'is_active'])
            ->map(fn (self $unit): array => [
                'id' => $unit->id,
                'name' => $unit->name,
                'is_active' => $unit->is_active,
            ])
            ->values()
            ->all();
    }
}
