<?php
// CoreFlux/core/CLI/Commands/MakeDatabaseCommand.php

namespace Core\CLI\Commands;

use Core\CLI\Command;
use PDO;
use PDOException;

class MakeDatabaseCommand implements Command
{
    public function getName(): string
    {
        return 'make:database';
    }

    public function getDescription(): string
    {
        return 'Creates the database defined in app/config/database.php.';
    }

    public function execute(array $args): int
    {
        echo "Attempting to create database...\n";

        // Load database configuration
        $databaseConfigPath = APP_PATH . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
        if (!file_exists($databaseConfigPath)) {
            echo "Error: Database configuration file not found at '{$databaseConfigPath}'.\n";
            return 1;
        }
        $config = require $databaseConfigPath;

        // Extract necessary config for connection without a specific database
        $driver = $config['driver'];
        $host = $config['host'];
        $port = $config['port'];
        $dbName = $config['database'];
        $username = $config['username'];
        $password = $config['password'];
        $charset = $config['charset'];

        // DSN for connecting to the MySQL server WITHOUT specifying a database initially
        $dsn = "{$driver}:host={$host};port={$port};charset={$charset}";

        try {
            // Establish a PDO connection to the MySQL server
            $pdo = new PDO(
                $dsn,
                $username,
                $password,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]
            );

            // Execute the CREATE DATABASE statement
            $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET {$charset} COLLATE {$config['collation']}");

            echo "Success: Database '{$dbName}' created or already exists.\n";
            return 0; // Indicate success

        } catch (PDOException $e) {
            echo "Error: Failed to create database.\n";
            echo "Message: " . $e->getMessage() . "\n";
            echo "Please check your database credentials and ensure the user has CREATE privileges.\n";
            return 1; // Indicate error
        }
    }
}