<?php

/**
 * ============================================================
 *
 * @project   biiproject
 *
 * @author    Andika Debi Putra
 *
 * @email     andikadebiputra@gmail.com
 *
 * @website   https://biiproject.com
 *
 * @copyright Copyright (c) 2026 Andika Debi Putra
 * @license   Proprietary - All Rights Reserved
 *
 * @version   1.0.0
 *
 * @created   2026-05-01
 * ============================================================
 */

namespace App\Services\AI;

use App\Services\SystemConfig\SystemConfigService;
use Illuminate\Support\Facades\Cache;

class SecurityHardeningService
{
    public function __construct(
        protected AiService $aiService,
        protected SystemConfigService $configService
    ) {}

    /**
     * Audit system security settings and get AI recommendations.
     */
    public function auditSecurity(): array
    {
        if (! get_setting('ai_enabled', false)) {
            return ['error' => 'AI Service disabled.'];
        }

        // Collect relevant security settings
        $settings = [
            'force_https' => get_setting('force_https'),
            'hsts_enabled' => get_setting('hsts_enabled'),
            'two_factor_auth' => get_setting('two_factor_auth'),
            'password_min_length' => get_setting('password_min_length'),
            'login_max_attempts' => get_setting('login_max_attempts'),
            'session_lifetime' => get_setting('session_lifetime'),
            'ip_whitelist_admin' => ! empty(get_setting('ip_whitelist_admin')),
            'backup_db_encrypt' => get_setting('backup_db_encrypt'),
            'maintenance_mode' => get_setting('maintenance_mode_enabled'),
            'environment' => app()->environment(),
            'debug_mode' => config('app.debug'),
        ];

        $prompt = 'As a Cyber Security Expert, audit the following Laravel system security configurations and provide:
        1. A Security Score (0-100).
        2. Critical Vulnerabilities (if any).
        3. Hardening Recommendations.
        4. A JSON object summary at the end.

        CONFIGURATIONS:
        '.json_encode($settings, JSON_PRETTY_PRINT);

        try {
            return Cache::remember('security_audit_result', 86400, function () use ($prompt) {
                $result = $this->aiService->provider()->generate($prompt);

                if (isset($result['success']) && $result['success']) {
                    return [
                        'analysis' => $result['response'],
                        'score' => $this->extractScore($result['response']),
                        'timestamp' => now()->toDateTimeString(),
                    ];
                }

                return ['error' => $result['error'] ?? 'Unknown error'];
            });
        } catch (\Exception $e) {
            return ['error' => $e->getMessage()];
        }
    }

    private function extractScore(string $text): int
    {
        preg_match('/Score:?\s*(\d+)/i', $text, $matches);

        return isset($matches[1]) ? (int) $matches[1] : 70;
    }
}
