<?php

/**
 * Module Creation Script
 * 
 * Usage: php scripts/create_module.php ModuleName
 * Example: php scripts/create_module.php Stripe
 */

if ($argc < 2) {
    echo "Usage: php scripts/create_module.php ModuleName\n";
    echo "Example: php scripts/create_module.php Stripe\n";
    exit(1);
}

$moduleName = $argv[1];
$moduleNameLower = strtolower($moduleName);

echo "Creating module: {$moduleName}\n";
echo "Module name (lowercase): {$moduleNameLower}\n\n";

// Create directory structure
$baseDir = "app/Modules/{$moduleName}";
$dirs = [
    $baseDir,
    "{$baseDir}/controllers",
    "{$baseDir}/controllers/api",
    "{$baseDir}/controllers/api/v1",
    "{$baseDir}/models",
    "{$baseDir}/services",
    "{$baseDir}/views",
];

foreach ($dirs as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
        echo "✅ Created directory: {$dir}\n";
    }
}

// Create Service Provider
$serviceProviderContent = str_replace(
    ['{ModuleName}', '{module_name}'],
    [$moduleName, $moduleNameLower],
    file_get_contents('docs/MODULE_PATTERN_TEMPLATE.md')
);

// Extract service provider template
preg_match('/### Template: `{ModuleName}ServiceProvider\.php`\s*```php\s*(.*?)\s*```/s', $serviceProviderContent, $matches);
if (isset($matches[1])) {
    $serviceProviderTemplate = $matches[1];
    $serviceProviderTemplate = str_replace(
        ['{ModuleName}', '{module_name}'],
        [$moduleName, $moduleNameLower],
        $serviceProviderTemplate
    );
    
    file_put_contents("{$baseDir}/{$moduleName}ServiceProvider.php", $serviceProviderTemplate);
    echo "✅ Created: {$baseDir}/{$moduleName}ServiceProvider.php\n";
}

// Create Service Interface
preg_match('/### Template: `{ModuleName}ServiceInterface\.php`\s*```php\s*(.*?)\s*```/s', $serviceProviderContent, $matches);
if (isset($matches[1])) {
    $interfaceTemplate = $matches[1];
    $interfaceTemplate = str_replace(
        ['{ModuleName}', '{module_name}'],
        [$moduleName, $moduleNameLower],
        $interfaceTemplate
    );
    
    file_put_contents("{$baseDir}/services/{$moduleName}ServiceInterface.php", $interfaceTemplate);
    echo "✅ Created: {$baseDir}/services/{$moduleName}ServiceInterface.php\n";
}

// Create Service Implementation
preg_match('/### Template: `{ModuleName}Service\.php`\s*```php\s*(.*?)\s*```/s', $serviceProviderContent, $matches);
if (isset($matches[1])) {
    $serviceTemplate = $matches[1];
    $serviceTemplate = str_replace(
        ['{ModuleName}', '{module_name}', '{MODULE_NAME}'],
        [$moduleName, $moduleNameLower, strtoupper($moduleNameLower)],
        $serviceTemplate
    );
    
    file_put_contents("{$baseDir}/services/{$moduleName}Service.php", $serviceTemplate);
    echo "✅ Created: {$baseDir}/services/{$moduleName}Service.php\n";
}

// Create Auth Service
preg_match('/### Template: `{ModuleName}AuthService\.php`\s*```php\s*(.*?)\s*```/s', $serviceProviderContent, $matches);
if (isset($matches[1])) {
    $authTemplate = $matches[1];
    $authTemplate = str_replace(
        ['{ModuleName}', '{module_name}', '{MODULE_NAME}'],
        [$moduleName, $moduleNameLower, strtoupper($moduleNameLower)],
        $authTemplate
    );
    
    file_put_contents("{$baseDir}/services/{$moduleName}AuthService.php", $authTemplate);
    echo "✅ Created: {$baseDir}/services/{$moduleName}AuthService.php\n";
}

// Create Configuration File
$configContent = "<?php\n\nreturn [\n";
$configContent .= "    /*\n";
$configContent .= "    |--------------------------------------------------------------------------\n";
$configContent .= "    | {$moduleName} Configuration\n";
$configContent .= "    |--------------------------------------------------------------------------\n";
$configContent .= "    |\n";
$configContent .= "    | Configuration settings for {$moduleName} module\n";
$configContent .= "    |\n";
$configContent .= "    */\n\n";
$configContent .= "    // API Configuration\n";
$configContent .= "    'base_url' => env('" . strtoupper($moduleNameLower) . "_BASE_URL', 'https://api.example.com'),\n";
$configContent .= "    'timeout' => env('" . strtoupper($moduleNameLower) . "_TIMEOUT', 30),\n\n";
$configContent .= "    // Authentication\n";
$configContent .= "    'client_id' => env('" . strtoupper($moduleNameLower) . "_CLIENT_ID'),\n";
$configContent .= "    'client_secret' => env('" . strtoupper($moduleNameLower) . "_CLIENT_SECRET'),\n\n";
$configContent .= "    // Default Settings\n";
$configContent .= "    'defaults' => [\n";
$configContent .= "        'status' => 'active',\n";
$configContent .= "        'type' => 'standard',\n";
$configContent .= "    ],\n\n";
$configContent .= "    // Logging\n";
$configContent .= "    'log_prefix' => '[{$moduleName}]',\n";
$configContent .= "    'log_level' => env('" . strtoupper($moduleNameLower) . "_LOG_LEVEL', 'info'),\n\n";
$configContent .= "    // Cache Settings\n";
$configContent .= "    'cache_ttl' => env('" . strtoupper($moduleNameLower) . "_CACHE_TTL', 3600), // 1 hour\n\n";
$configContent .= "    // API Endpoints\n";
$configContent .= "    'endpoints' => [\n";
$configContent .= "        'base' => '/api/v1',\n";
$configContent .= "        'auth' => '/oauth/token',\n";
$configContent .= "        'data' => '/data',\n";
$configContent .= "    ],\n";
$configContent .= "];\n";

file_put_contents("config/{$moduleNameLower}.php", $configContent);
echo "✅ Created: config/{$moduleNameLower}.php\n";

// Create Test File
$testContent = "<?php\n\n";
$testContent .= "namespace Tests\Feature;\n\n";
$testContent .= "use Tests\TestCase;\n";
$testContent .= "use App\Modules\\{$moduleName}\Services\\{$moduleName}ServiceInterface;\n";
$testContent .= "use App\Modules\\{$moduleName}\Services\\{$moduleName}AuthService;\n";
$testContent .= "use Illuminate\Foundation\Testing\RefreshDatabase;\n\n";
$testContent .= "class {$moduleName}Test extends TestCase\n";
$testContent .= "{\n";
$testContent .= "    use RefreshDatabase;\n\n";
$testContent .= "    public function test_service_interface_binding()\n";
$testContent .= "    {\n";
$testContent .= "        \$service = app({$moduleName}ServiceInterface::class);\n\n";
$testContent .= "        \$this->assertInstanceOf({$moduleName}ServiceInterface::class, \$service);\n";
$testContent .= "    }\n\n";
$testContent .= "    public function test_auth_service_singleton()\n";
$testContent .= "    {\n";
$testContent .= "        \$auth1 = app({$moduleName}AuthService::class);\n";
$testContent .= "        \$auth2 = app({$moduleName}AuthService::class);\n\n";
$testContent .= "        \$this->assertSame(\$auth1, \$auth2);\n";
$testContent .= "    }\n\n";
$testContent .= "    public function test_service_alias_binding()\n";
$testContent .= "    {\n";
$testContent .= "        \$service = app('{$moduleNameLower}');\n\n";
$testContent .= "        \$this->assertInstanceOf({$moduleName}ServiceInterface::class, \$service);\n";
$testContent .= "    }\n";
$testContent .= "}\n";

file_put_contents("tests/Feature/{$moduleName}Test.php", $testContent);
echo "✅ Created: tests/Feature/{$moduleName}Test.php\n";

// Create README
$readmeContent = "# {$moduleName} Module\n\n";
$readmeContent .= "This module follows the Laravel module pattern established in the project.\n\n";
$readmeContent .= "## Features\n\n";
$readmeContent .= "- Interface-based service architecture\n";
$readmeContent .= "- Singleton binding for performance\n";
$readmeContent .= "- Centralized authentication service\n";
$readmeContent .= "- Comprehensive logging\n";
$readmeContent .= "- Configuration management\n\n";
$readmeContent .= "## Usage\n\n";
$readmeContent .= "```php\n";
$readmeContent .= "// Via interface\n";
$readmeContent .= "\$service = app({$moduleName}ServiceInterface::class);\n";
$readmeContent .= "\$result = \$service->processData(\$data);\n\n";
$readmeContent .= "// Via alias\n";
$readmeContent .= "\$service = app('{$moduleNameLower}');\n";
$readmeContent .= "\$result = \$service->processData(\$data);\n";
$readmeContent .= "```\n\n";
$readmeContent .= "## Configuration\n\n";
$readmeContent .= "Add to your `.env` file:\n\n";
$readmeContent .= "```env\n";
$readmeContent .= "# {$moduleName} Configuration\n";
$readmeContent .= strtoupper($moduleNameLower) . "_BASE_URL=https://api.example.com\n";
$readmeContent .= strtoupper($moduleNameLower) . "_CLIENT_ID=your_client_id\n";
$readmeContent .= strtoupper($moduleNameLower) . "_CLIENT_SECRET=your_client_secret\n";
$readmeContent .= strtoupper($moduleNameLower) . "_TIMEOUT=30\n";
$readmeContent .= strtoupper($moduleNameLower) . "_LOG_LEVEL=info\n";
$readmeContent .= strtoupper($moduleNameLower) . "_CACHE_TTL=3600\n";
$readmeContent .= "```\n\n";
$readmeContent .= "## Testing\n\n";
$readmeContent .= "```bash\n";
$readmeContent .= "docker-compose exec app php artisan test tests/Feature/{$moduleName}Test.php\n";
$readmeContent .= "```\n";

file_put_contents("{$baseDir}/README.md", $readmeContent);
echo "✅ Created: {$baseDir}/README.md\n";

// Create routes file
$routesContent = "<?php\n\n";
$routesContent .= "// {$moduleName} Module Routes\n";
$routesContent .= "// Add your routes here\n\n";
$routesContent .= "Route::group(['prefix' => '{$moduleNameLower}', 'middleware' => ['auth']], function () {\n";
$routesContent .= "    // API Routes\n";
$routesContent .= "    Route::group(['prefix' => 'api/v1'], function () {\n";
$routesContent .= "        // Add your API routes here\n";
$routesContent .= "    });\n\n";
$routesContent .= "    // Web Routes\n";
$routesContent .= "    Route::group([], function () {\n";
$routesContent .= "        // Add your web routes here\n";
$routesContent .= "    });\n";
$routesContent .= "});\n";

file_put_contents("{$baseDir}/routes.php", $routesContent);
echo "✅ Created: {$baseDir}/routes.php\n";

echo "\n🎉 Module '{$moduleName}' created successfully!\n\n";
echo "📋 Next Steps:\n";
echo "1. Update config/app.php to register the service provider:\n";
echo "   'App\\Modules\\{$moduleName}\\{$moduleName}ServiceProvider',\n\n";
echo "2. Add environment variables to your .env file\n";
echo "3. Clear Laravel cache: docker-compose exec app php artisan config:clear\n";
echo "4. Run tests: docker-compose exec app php artisan test tests/Feature/{$moduleName}Test.php\n";
echo "5. Implement your business logic in the service classes\n\n";
echo "📚 See docs/MODULE_PATTERN_TEMPLATE.md for detailed patterns and best practices.\n"; 