<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class BackupDatabase extends Command
{
    protected $signature = 'backup:database';

    protected $description = 'Create a database backup snapshot';

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

        $backupDir = storage_path('app/backups');
        File::ensureDirectoryExists($backupDir);

        $filename = 'backup_'.now()->format('Y-m-d_His').'.sql';
        $path = $backupDir.DIRECTORY_SEPARATOR.$filename;

        if ($driver === 'sqlite') {
            $database = config("database.connections.{$connection}.database");
            File::copy($database, $path);

            $this->info("SQLite backup created: {$filename}");

            return self::SUCCESS;
        }

        if ($driver === 'mysql') {
            $host = config("database.connections.{$connection}.host");
            $port = config("database.connections.{$connection}.port");
            $database = config("database.connections.{$connection}.database");
            $username = config("database.connections.{$connection}.username");
            $password = config("database.connections.{$connection}.password");

            $command = sprintf(
                'mysqldump --host=%s --port=%s --user=%s %s > %s',
                escapeshellarg($host),
                escapeshellarg($port),
                escapeshellarg($username),
                escapeshellarg($database),
                escapeshellarg($path),
            );

            if ($password) {
                putenv('MYSQL_PWD='.$password);
            }

            exec($command, $output, $exitCode);

            if ($exitCode !== 0) {
                $this->error('mysqldump failed. Ensure mysqldump is available on PATH.');

                return self::FAILURE;
            }

            $this->info("MySQL backup created: {$filename}");

            return self::SUCCESS;
        }

        $this->error("Backup not supported for driver: {$driver}");

        return self::FAILURE;
    }
}
