<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Service;

use OCP\IConfig;
use OCP\Security\ICrypto;

/**
 * Read/write backup configuration stored in Nextcloud's app config.
 *
 * Settings:
 * - backup_schedule: 'daily' | 'weekly' | 'disabled' (default 'disabled')
 * - backup_retention_count: int (default 10)
 * - backup_password: encrypted string (optional, for automated backups)
 */
class BackupSettingsService {

    private const APP_ID = 'mitgliederverwaltung';

    private IConfig $config;
    private ICrypto $crypto;

    public function __construct(IConfig $config, ICrypto $crypto) {
        $this->config = $config;
        $this->crypto = $crypto;
    }

    public function getSchedule(): string {
        return $this->config->getAppValue(self::APP_ID, 'backup_schedule', 'disabled');
    }

    public function setSchedule(string $schedule): void {
        $valid = ['daily', 'weekly', 'disabled'];
        if (!in_array($schedule, $valid, true)) {
            throw new ValidationException('Ungueltiger Zeitplan: ' . $schedule);
        }
        $this->config->setAppValue(self::APP_ID, 'backup_schedule', $schedule);
    }

    public function getRetentionCount(): int {
        return (int) $this->config->getAppValue(self::APP_ID, 'backup_retention_count', '10');
    }

    public function setRetentionCount(int $count): void {
        if ($count < 1) {
            throw new ValidationException('Aufbewahrungsanzahl muss mindestens 1 sein');
        }
        $this->config->setAppValue(self::APP_ID, 'backup_retention_count', (string) $count);
    }

    public function getBackupPassword(): ?string {
        $encrypted = $this->config->getAppValue(self::APP_ID, 'backup_password', '');
        if ($encrypted === '') {
            return null;
        }
        try {
            return $this->crypto->decrypt($encrypted);
        } catch (\Exception $e) {
            return null;
        }
    }

    public function setBackupPassword(?string $password): void {
        if ($password === null || $password === '') {
            $this->config->setAppValue(self::APP_ID, 'backup_password', '');
        } else {
            $this->config->setAppValue(self::APP_ID, 'backup_password', $this->crypto->encrypt($password));
        }
    }

    public function getAllSettings(): array {
        return [
            'schedule' => $this->getSchedule(),
            'retentionCount' => $this->getRetentionCount(),
            'hasPassword' => $this->getBackupPassword() !== null,
        ];
    }

    public function updateSettings(array $data): void {
        if (isset($data['schedule'])) {
            $this->setSchedule($data['schedule']);
        }
        if (isset($data['retentionCount'])) {
            $this->setRetentionCount((int) $data['retentionCount']);
        }
        if (array_key_exists('password', $data)) {
            $this->setBackupPassword($data['password']);
        }
    }
}
