<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\BackgroundJob;

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

/**
 * Nightly background job that runs a full contacts reconciliation.
 *
 * Part of Issue #51.
 */
class ContactsFullSyncJob extends TimedJob {

    private ContactsSyncService $contactsSyncService;
    private LoggerInterface $logger;

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

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

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

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