<?php

declare(strict_types=1);

namespace App\Framework\Admin\Factories;

use App\Framework\Admin\ValueObjects\AdminTableConfig;
use App\Framework\View\Table\Formatters;
use App\Framework\View\Table\Table;
use App\Framework\View\Table\TableOptions;

/**
 * Admin Table Factory
 *
 * Creates admin tables using the existing Table module
 */
final readonly class AdminTableFactory
{
    public function create(AdminTableConfig $config, array $data): Table
    {
        // Build column definitions from config
        $columnDefs = [];
        foreach ($config->columns as $key => $columnConfig) {
            $columnDefs[$key] = [
                'header' => $columnConfig['label'],
                'sortable' => $columnConfig['sortable'] ?? $config->sortable,
                'formatter' => $this->getFormatter($columnConfig['formatter'] ?? null),
                'class' => $columnConfig['class'] ?? null,
            ];
        }

        // Build table options with data attributes for JavaScript
        $options = TableOptions::admin()
            ->withId($config->resource . 'Table')
            ->withDataAttributes([
                'resource' => $config->resource,
                'api-endpoint' => $config->getApiEndpoint(),
                'sortable' => $config->sortable ? 'true' : 'false',
                'searchable' => $config->searchable ? 'true' : 'false',
                'paginated' => $config->paginated ? 'true' : 'false',
                'per-page' => (string) $config->perPage,
            ]);

        // Use existing Table::fromArray
        return Table::fromArray(
            data: $data,
            columnDefs: $columnDefs,
            options: $options
        );
    }

    private function getFormatter(?string $type): mixed
    {
        return match ($type) {
            'date' => new Formatters\DateFormatter(),
            'status' => Formatters\StatusFormatter::withBadges(),
            'boolean' => Formatters\BooleanFormatter::germanWithBadges(),
            'currency' => new Formatters\CurrencyFormatter(),
            'number' => new Formatters\NumberFormatter(),
            'masked' => new Formatters\MaskedFormatter(),
            default => null,
        };
    }
}
