<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Concerns;

use Builder\Core\Foundation\Tables\Column;
use Illuminate\Database\Eloquent\Model;

trait HasColumnFormats
{
    /**
     * Apply column format Closures to a record, returning it as an array.
     * Called via $paginator->through() only when at least one column has a formatter.
     *
     * The format closure receives three arguments: ($value, $record, $locale).
     * $value is the raw value from the data array (null for virtual/computed columns).
     * $record is the original Eloquent model instance with eager-loaded relations.
     * $locale is the current content locale (null for non-translatable resources).
     *
     * @param  list<Column>  $columns
     * @return array<string, mixed>
     */
    protected function applyColumnFormats(mixed $item, array $columns, ?string $locale = null): array
    {
        $data = ($item instanceof Model) ? $item->toArray() : (array) $item;

        foreach ($columns as $column) {
            $format = $column->getFormat();

            if ($format === null) {
                continue;
            }

            $key = $column->getKey();
            $data[$key] = $format($data[$key] ?? null, $item, $locale);
        }

        return $data;
    }
}
