<?php

namespace App\Modules\AntiTheft\Application;

use App\Modules\AntiTheft\Domain\RiskLevel;
use App\Modules\AntiTheft\Domain\Sensitivity;
use App\Modules\AntiTheft\Domain\SignalType;
use App\Modules\AntiTheft\Domain\TheftRule;

final class DefaultRuleCatalog implements RuleProvider
{
    /** @return array<int, TheftRule> */
    public function forDevice(string $deviceUuid): iterable
    {
        return [
            $this->rule('motion', 'Motion detected while armed', SignalType::Motion, RiskLevel::Medium, 400, 0.72, 2.8, Sensitivity::Balanced),
            $this->rule('pocket-removed', 'Device removed from pocket', SignalType::PocketRemoved, RiskLevel::High, 650, 0.78),
            $this->rule('charging-removed', 'Charging cable removed', SignalType::ChargingRemoved, RiskLevel::High, 700, 0.90),
            $this->rule('picked-up', 'Device picked up', SignalType::DevicePickedUp, RiskLevel::Medium, 450, 0.75, 1.6),
            $this->rule('sudden-movement', 'Sudden movement detected', SignalType::SuddenMovement, RiskLevel::High, 750, 0.80, 5.0, Sensitivity::High),
            $this->rule('app-pin-failed', 'Repeated app PIN failures', SignalType::AppUnlockFailed, RiskLevel::Critical, 1000, 0.95),
            $this->rule('screen-unlocked', 'Screen unlocked while armed', SignalType::ScreenUnlocked, RiskLevel::Medium, 350, 0.90),
            $this->rule('sim-changed', 'SIM card changed', SignalType::SimChanged, RiskLevel::Critical, 980, 0.95),
            $this->rule('sim-removed', 'SIM card removed', SignalType::SimRemoved, RiskLevel::Critical, 990, 0.95),
            $this->rule('airplane-mode', 'Airplane mode enabled', SignalType::AirplaneModeEnabled, RiskLevel::High, 820, 0.90),
            $this->rule('network-disconnected', 'Network disconnected', SignalType::NetworkDisconnected, RiskLevel::Medium, 300, 0.85),
            $this->rule('bluetooth-disconnected', 'Trusted Bluetooth disconnected', SignalType::BluetoothDisconnected, RiskLevel::Medium, 325, 0.85),
            $this->rule('unknown-charger', 'Unknown charger connected', SignalType::UnknownCharger, RiskLevel::Medium, 375, 0.75),
            $this->rule('device-offline', 'Device offline beyond threshold', SignalType::DeviceOffline, RiskLevel::High, 850, 0.95),
        ];
    }

    private function rule(
        string $code,
        string $name,
        SignalType $signal,
        RiskLevel $risk,
        int $priority,
        float $confidence,
        float $magnitude = 0.0,
        Sensitivity $sensitivity = Sensitivity::Balanced,
    ): TheftRule {
        return new TheftRule(
            code: $code,
            name: $name,
            signal: $signal,
            risk: $risk,
            priority: $priority,
            minimumConfidence: $confidence,
            magnitudeThreshold: $magnitude,
            sensitivity: $sensitivity,
            cooldownSeconds: in_array($risk, [RiskLevel::Critical, RiskLevel::High], true) ? 60 : 120,
        );
    }
}
