<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Command;

use OCA\Mitgliederverwaltung\Service\BackupService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class BackupCreateCommand extends Command {

    private BackupService $backupService;

    public function __construct(BackupService $backupService) {
        parent::__construct();
        $this->backupService = $backupService;
    }

    protected function configure(): void {
        $this->setName('mitgliederverwaltung:backup:create')
            ->setDescription('Create a full backup of Mitgliederverwaltung data')
            ->addOption('password', 'p', InputOption::VALUE_OPTIONAL, 'Password for ZIP encryption');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int {
        $password = $input->getOption('password');

        $output->writeln('Creating backup...');

        try {
            $result = $this->backupService->createBackup($password, 'cli');

            $output->writeln('');
            $output->writeln('<info>Backup created successfully!</info>');
            $output->writeln('  Filename: ' . $result['filename']);
            $output->writeln('  Size:     ' . $this->formatBytes($result['size']));
            $output->writeln('  Created:  ' . $result['createdAt']);
            $output->writeln('');

            $totalRows = 0;
            foreach ($result['tables'] as $table => $count) {
                if ($count > 0) {
                    $output->writeln("  {$table}: {$count} rows");
                }
                $totalRows += $count;
            }
            $output->writeln('');
            $output->writeln("  Total: {$totalRows} rows across " . count($result['tables']) . ' tables');

            return Command::SUCCESS;
        } catch (\Exception $e) {
            $output->writeln('<error>Backup failed: ' . $e->getMessage() . '</error>');
            return Command::FAILURE;
        }
    }

    private function formatBytes(int $bytes): string {
        if ($bytes >= 1048576) {
            return round($bytes / 1048576, 2) . ' MB';
        }
        if ($bytes >= 1024) {
            return round($bytes / 1024, 2) . ' KB';
        }
        return $bytes . ' B';
    }
}
