<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Concerns;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

/**
 * Default implementation for CommandPaletteSearchable.
 * Uses the first searchable field as title and the second (if present) as subtitle.
 * For translatable models, falls back to any loaded translation when the base attribute is null.
 */
trait HasCommandPaletteSearch
{
    public function searchResultTitle(Model $record): string
    {
        $fields = $this->resolveSearchFields();
        $field = $fields[0] ?? null;

        if ($field === null) {
            return (string) $record->getKey();
        }

        return (string) ($this->resolveField($record, $field) ?? $record->getKey());
    }

    public function searchResultSubtitle(Model $record): ?string
    {
        $fields = $this->resolveSearchFields();

        if (count($fields) < 2) {
            return null;
        }

        $value = $this->resolveField($record, $fields[1]);

        return $value !== null ? (string) $value : null;
    }

    /** @return list<string> */
    private function resolveSearchFields(): array
    {
        $explicit = $this->searchable();

        if ($explicit !== []) {
            return $explicit;
        }

        $fromColumns = [];

        foreach ($this->columns() as $column) {
            if ($column->isSearchable()) {
                $fromColumns[] = $column->getKey();
            }
        }

        return $fromColumns;
    }

    private function resolveField(Model $record, string $field): mixed
    {
        $isTranslatable = method_exists($record, 'getTranslatableAttributes')
            && in_array($field, $record->getTranslatableAttributes(), true);

        $translationsLoaded = $record->relationLoaded('translations');

        if (! $isTranslatable || ! $translationsLoaded) {
            return $record->getAttribute($field);
        }

        $matchedLocale = $record->getAttribute('_matched_locale');

        /** @var Collection<int, Model> $translations */
        $translations = $record->getAttribute('translations');

        if ($matchedLocale) {
            $translation = $translations->firstWhere('locale', $matchedLocale);

            if ($translation && ($val = $translation->{$field}) !== null) {
                return $val;
            }
        }

        foreach ($translations as $translation) {
            if (($val = $translation->{$field}) !== null) {
                return $val;
            }
        }

        return null;
    }
}
