<?php

declare(strict_types=1);

namespace App\Framework\View\Table\Generators;

use App\Framework\View\Table\Table;
use App\Framework\View\Table\TableColumn;
use App\Framework\View\Table\TableGenerator;
use App\Framework\View\Table\TableOptions;
use App\Framework\View\Table\TableRow;

final readonly class EnvironmentTableGenerator implements TableGenerator
{
    public function generate(object|array $data, ?TableOptions $options = null): Table
    {
        if (! is_array($data)) {
            throw new \InvalidArgumentException('EnvironmentTableGenerator expects array data');
        }

        $columns = [
            TableColumn::text('key', 'Variable', 'env-key'),
            new TableColumn(
                key: 'value',
                header: 'Wert',
                cssClass: 'env-value',
                formatter: $this->createValueFormatter()
            ),
        ];

        $rows = [];
        foreach ($data as $item) {
            // Handle both associative arrays and objects
            $key = is_array($item) ? $item['key'] : $item->key;
            $value = is_array($item) ? $item['value'] : $item->value;

            $rows[] = TableRow::fromData([
                'key' => $key,
                'value' => $value,
            ], $columns, 'env-row');
        }

        $tableOptions = $options ?? TableOptions::admin();

        return new Table(
            columns: $columns,
            rows: $rows,
            cssClass: 'admin-table',
            options: $tableOptions,
            id: 'envTable'
        );
    }

    public function supports(object|array $data): bool
    {
        if (! is_array($data) || empty($data)) {
            return false;
        }

        $firstItem = reset($data);
        if (! is_array($firstItem) && ! is_object($firstItem)) {
            return false;
        }

        // Check if it has key/value structure
        if (is_array($firstItem)) {
            return isset($firstItem['key']) && isset($firstItem['value']);
        }

        // Check if object has key/value properties
        return property_exists($firstItem, 'key') && property_exists($firstItem, 'value');
    }

    private function createValueFormatter(): \App\Framework\View\Table\CellFormatter
    {
        return new class () implements \App\Framework\View\Table\CellFormatter {
            public function format(mixed $value): string
            {
                if ($value === null || $value === '') {
                    return '';
                }

                $stringValue = (string) $value;

                // Already masked values pass through
                if ($stringValue === '********') {
                    return $stringValue;
                }

                return htmlspecialchars($stringValue, ENT_QUOTES);
            }
        };
    }
}
