<?php

declare(strict_types=1);

namespace PortalPeople\consoletools\services;

use Yii;

/**
 * ConsoleService – Gii model generation via Yii console application.
 *
 * SECURITY NOTE: This service spins up a full Yii console application
 * and invokes the Gii model generator. Access should be restricted to
 * trusted admin users only. Ensure the API endpoint is protected behind
 * appropriate authentication and authorisation guards before exposing it.
 */
class ConsoleService
{
    /**
     * Generate ActiveRecord models for the given table using Gii.
     *
     * @param string $table      Database table name.
     * @param string $connection Application component name for the DB connection.
     * @return mixed             Output from Gii or error message.
     */
    public function giimodel(string $table, string $connection): mixed
    {
        if (! defined('STDOUT')) {
            define('STDOUT', fopen('stdout', 'w'));
        }

        $modelname = ucwords(str_replace(['-', '_'], '', $table));
        $oldApp = Yii::$app;

        new \yii\console\Application([
            'bootstrap' => ['log', 'gii'],
            'id'        => 'Command runner',
            'basePath'  => '@api',
            'components' => [
                'db'         => Yii::$app->db,
                $connection  => Yii::$app->$connection,
                'log'        => [
                    'targets' => [
                        [
                            'class'  => 'yii\log\FileTarget',
                            'levels' => ['error', 'warning', 'trace'],
                        ],
                    ],
                ],
            ],
            'modules' => [
                'gii' => [
                    'class'      => 'yii\gii\Module',
                    'generators' => [
                        'crud' => [
                            'class'     => 'yii\gii\generators\crud\Generator',
                            'templates' => [
                                'Chalvington-Crud' => __DIR__ . '/../../../../../../../NGauge_Base/common/components/Gii/crud/chalvington',
                            ],
                        ],
                        'model' => [
                            'class' => 'common\components\Gii\model\Generator',
                        ],
                    ],
                ],
            ],
        ]);

        Yii::$app->runAction('gii/model', [
            'tableName'  => $table,
            'modelClass' => $modelname,
            'queryNs'    => 'api\\modules\\v1\\models',
            'db'         => $connection,
            'ns'         => 'api\\modules\\v1\\models',
            'overwrite'  => true,
            'interactive' => false,
        ]);

        Yii::$app->end();
        Yii::$app = $oldApp;

        return ['status' => 200, 'message' => 'Model generated for table: ' . $table];
    }
}
