<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\BackgroundJob;

use OCA\Mitgliederverwaltung\Service\BackupService;
use OCA\Mitgliederverwaltung\Service\BackupSettingsService;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\TimedJob;
use Psr\Log\LoggerInterface;

/**
 * Background job for scheduled automatic backups.
 *
 * Runs every 24 hours. Checks the configured schedule ('daily', 'weekly', 'disabled')
 * and creates a backup if due. Automatically rotates old backups.
 */
class BackupJob extends TimedJob {

    private BackupService $backupService;
    private BackupSettingsService $settingsService;
    private LoggerInterface $logger;

    public function __construct(
        ITimeFactory $time,
        BackupService $backupService,
        BackupSettingsService $settingsService,
        LoggerInterface $logger
    ) {
        parent::__construct($time);
        $this->backupService = $backupService;
        $this->settingsService = $settingsService;
        $this->logger = $logger;

        // Check every 24 hours
        $this->setInterval(24 * 60 * 60);
    }

    protected function run($argument): void {
        $schedule = $this->settingsService->getSchedule();

        if ($schedule === 'disabled') {
            return;
        }

        // For weekly schedule, only run if 7+ days since last backup
        if ($schedule === 'weekly') {
            $backups = $this->backupService->listBackups();
            if (!empty($backups)) {
                $lastCreated = strtotime($backups[0]['createdAt']);
                $daysSince = (time() - $lastCreated) / 86400;
                if ($daysSince < 7) {
                    return;
                }
            }
        }

        try {
            $password = $this->settingsService->getBackupPassword();
            $result = $this->backupService->createBackup($password, 'scheduled');
            $deleted = $this->backupService->rotateBackups();

            $this->logger->info('Scheduled backup completed', [
                'filename' => $result['filename'],
                'rotated' => $deleted,
                'app' => 'mitgliederverwaltung',
            ]);
        } catch (\Exception $e) {
            $this->logger->error('Scheduled backup failed', [
                'exception' => $e,
                'app' => 'mitgliederverwaltung',
            ]);
        }
    }
}
