<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Command;

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

class BackupListCommand extends Command {

    private BackupService $backupService;

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

    protected function configure(): void {
        $this->setName('mitgliederverwaltung:backup:list')
            ->setDescription('List all available backups');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int {
        $backups = $this->backupService->listBackups();

        if (empty($backups)) {
            $output->writeln('No backups found.');
            return Command::SUCCESS;
        }

        $table = new Table($output);
        $table->setHeaders(['Filename', 'Created', 'Size', 'Tables', 'Rows', 'Triggered By']);

        foreach ($backups as $backup) {
            $totalRows = 0;
            foreach ($backup['tables'] as $count) {
                $totalRows += $count;
            }

            $table->addRow([
                $backup['filename'],
                $backup['createdAt'],
                $this->formatBytes($backup['size']),
                count($backup['tables']),
                $totalRows,
                $backup['triggeredBy'] ?? '-',
            ]);
        }

        $table->render();

        return Command::SUCCESS;
    }

    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';
    }
}
