<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PDO;
use PDOException;

class CreateDatabaseCommand extends Command
{
    protected $signature = 'db:create';

    protected $description = 'Create the MySQL database named in DB_DATABASE if it does not exist';

    public function handle(): int
    {
        $connection = config('database.default');

        if ($connection !== 'mysql' && $connection !== 'mariadb') {
            $this->error('This command only supports mysql/mariadb. Current connection: '.$connection);

            return self::FAILURE;
        }

        $config = config('database.connections.'.$connection);
        $database = $config['database'] ?? '';

        if ($database === '' || $database === null) {
            $this->error('DB_DATABASE is empty in .env');

            return self::FAILURE;
        }

        if (! preg_match('/^[a-zA-Z0-9_]+$/', $database)) {
            $this->error('DB_DATABASE may only contain letters, numbers, and underscores.');

            return self::FAILURE;
        }

        $host = $config['host'] ?? '127.0.0.1';
        $port = (int) ($config['port'] ?? 3306);
        $username = $config['username'] ?? 'root';
        $password = $config['password'] ?? '';

        try {
            $pdo = new PDO(
                sprintf('mysql:host=%s;port=%d', $host, $port),
                $username,
                $password,
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
            );
        } catch (PDOException $e) {
            $this->error('Could not connect to MySQL: '.$e->getMessage());
            $this->comment('Check DB_HOST, DB_PORT, DB_USERNAME, DB_PASSWORD in .env and that MySQL is running.');

            return self::FAILURE;
        }

        $pdo->exec(sprintf(
            'CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci',
            $database
        ));

        $this->info('Database ready: '.$database);

        return self::SUCCESS;
    }
}
