<?php

namespace App\Modules\Pilkades\Services;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
use Symfony\Component\Process\Process;

class DatabaseBackupService
{
    public function backupDirectory(): string
    {
        $path = storage_path('app/backups');

        if (! File::isDirectory($path)) {
            File::makeDirectory($path, 0755, true);
        }

        return $path;
    }

    public function listBackups(): array
    {
        return collect(File::files($this->backupDirectory()))
            ->sortByDesc(fn ($file) => $file->getMTime())
            ->map(fn ($file) => [
                'name' => $file->getFilename(),
                'size' => $file->getSize(),
                'created_at' => date('Y-m-d H:i:s', $file->getMTime()),
            ])
            ->values()
            ->all();
    }

    /**
     * Dump the database using the CLI tool matching the active connection
     * driver (mysqldump for MySQL, sqlite3 copy for SQLite). Shared-hosting
     * friendly: no extra Composer package, just the OS-provided binary.
     */
    public function createBackup(): string
    {
        $connection = Config::get('database.default');
        $config = Config::get("database.connections.{$connection}");
        $filename = 'backup-'.now()->format('Y_m_d_His').'.sql';
        $destination = $this->backupDirectory().DIRECTORY_SEPARATOR.$filename;

        if ($config['driver'] === 'sqlite') {
            File::copy($config['database'], $this->backupDirectory().DIRECTORY_SEPARATOR.'backup-'.now()->format('Y_m_d_His').'.sqlite');

            return $filename;
        }

        $process = new Process([
            'mysqldump',
            '-h', $config['host'] ?? '127.0.0.1',
            '-P', (string) ($config['port'] ?? 3306),
            '-u', $config['username'],
            '--password='.$config['password'],
            $config['database'],
        ]);

        $process->setTimeout(300);
        $process->mustRun();

        File::put($destination, $process->getOutput());

        return $filename;
    }
}
