<?php

namespace Daylight\Core\Models\Concerns;

use Illuminate\Support\Collection;

trait IsRelatable
{
    /**
     * Default implementation for simple models with a 'name' field.
     */
    public static function searchForRelation(string $query, array $excludeIds = [], int $limit = 10): Collection
    {
        $queryBuilder = static::query();

        if (! empty($excludeIds)) {
            $queryBuilder->whereNotIn('id', $excludeIds);
        }

        $queryBuilder->where('name', 'LIKE', "%{$query}%");

        return $queryBuilder->limit($limit)
            ->get()
            ->map(fn ($item) => $item->formatForRelation());
    }

    /**
     * Default implementation to get items by IDs.
     */
    public static function getForRelation(array $ids): Collection
    {
        return static::whereIn('id', $ids)
            ->get()
            ->map(fn ($item) => $item->formatForRelation());
    }

    /**
     * Default formatting for simple models.
     */
    public function formatForRelation(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name ?? "#{$this->id}",
            'type' => class_basename(static::class),
        ];
    }
}
