<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\BackgroundJob;

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

/**
 * Nightly background job that runs a full calendar reconciliation.
 *
 * Catches any drift from missed queue events by comparing all members
 * with their calendar events and creating/updating/deleting as needed.
 *
 * Part of Issue #50.
 */
class CalendarFullSyncJob extends TimedJob {

    private CalendarSyncService $calendarSyncService;
    private LoggerInterface $logger;

    public function __construct(
        ITimeFactory $time,
        CalendarSyncService $calendarSyncService,
        LoggerInterface $logger
    ) {
        parent::__construct($time);
        $this->calendarSyncService = $calendarSyncService;
        $this->logger = $logger;

        // Run once per day (24 hours)
        $this->setInterval(24 * 60 * 60);
    }

    protected function run($argument): void {
        try {
            $stats = $this->calendarSyncService->fullSync();

            $this->logger->info('Calendar full sync completed', [
                'created' => $stats['created'],
                'updated' => $stats['updated'],
                'deleted' => $stats['deleted'],
                'app' => 'mitgliederverwaltung',
            ]);
        } catch (\Exception $e) {
            $this->logger->error('Calendar full sync failed', [
                'exception' => $e,
                'app' => 'mitgliederverwaltung',
            ]);
        }
    }
}
