<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\BackgroundJob;

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

/**
 * Background job that processes the sync queue every 5 minutes.
 *
 * Handles pending CalendarSync and ContactsSync entries.
 *
 * Part of Issues #50, #51.
 */
class SyncQueueJob extends TimedJob {

    private CalendarSyncService $calendarSyncService;
    private ContactsSyncService $contactsSyncService;
    private LoggerInterface $logger;

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

        // Run every 5 minutes
        $this->setInterval(5 * 60);
    }

    protected function run($argument): void {
        try {
            $calendarProcessed = $this->calendarSyncService->processQueue();
            $contactsProcessed = $this->contactsSyncService->processQueue();

            if ($calendarProcessed > 0 || $contactsProcessed > 0) {
                $this->logger->info('Sync queue processed', [
                    'calendar' => $calendarProcessed,
                    'contacts' => $contactsProcessed,
                    'app' => 'mitgliederverwaltung',
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('Sync queue processing failed', [
                'exception' => $e,
                'app' => 'mitgliederverwaltung',
            ]);
        }
    }
}
