<?php

declare(strict_types=1);

namespace App\Framework\Console\Result;

use App\Framework\Console\Components\Table;
use App\Framework\Console\ConsoleOutputInterface;
use App\Framework\Console\ExitCode;

/**
 * Table Result - Tabular data output
 *
 * Displays data in a formatted table with headers and rows.
 * Integrates with the existing Table component.
 *
 * Example:
 *   return TableResult::create(
 *       headers: ['ID', 'Name', 'Email'],
 *       rows: [['1', 'John', 'john@example.com']],
 *       title: 'Users'
 *   );
 */
final readonly class TableResult implements ConsoleResult
{
    public readonly array $data;

    /**
     * Create table result
     *
     * @param array<string> $headers Table headers
     * @param array<array<string>> $rows Table rows
     * @param string|null $title Optional table title
     * @param ExitCode $exitCode Exit code (default: SUCCESS)
     */
    public function __construct(
        public readonly array $headers,
        public readonly array $rows,
        public readonly ?string $title = null,
        public readonly ExitCode $exitCode = ExitCode::SUCCESS,
    ) {
        $this->data = [
            'headers' => $this->headers,
            'rows' => $this->rows,
            'title' => $this->title,
            'row_count' => count($this->rows),
            'exit_code' => $this->exitCode->value,
        ];
    }

    /**
     * Create table result (convenience factory)
     *
     * @param array<string> $headers
     * @param array<array<string>> $rows
     */
    public static function create(
        array $headers,
        array $rows,
        ?string $title = null,
        ExitCode $exitCode = ExitCode::SUCCESS
    ): self {
        return new self($headers, $rows, $title, $exitCode);
    }

    /**
     * Create empty table with headers only
     *
     * @param array<string> $headers
     */
    public static function empty(array $headers, ?string $title = null): self
    {
        return new self($headers, [], $title);
    }

    /**
     * Render table to console output
     */
    public function render(ConsoleOutputInterface $output): void
    {
        $table = new Table($output);

        if ($this->title !== null) {
            $table->setTitle($this->title);
        }

        $table->setHeaders($this->headers);
        $table->setRows($this->rows);
        $table->render();
    }
}
