<?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\Http\Controllers\AI;

use App\Http\Controllers\Controller;
use App\Services\AI\LogAnalysisService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class LogAnalysisController extends Controller
{
    public function __construct(
        protected LogAnalysisService $analysisService
    ) {}

    /**
     * Get the latest AI log analysis.
     */
    public function index()
    {
        $this->authorize('view ai log analysis');

        $analysis = Cache::get('ai_log_analysis_result', 'Analysis not generated yet. Click analyze to start.');

        return response()->json([
            'status' => 'success',
            'analysis' => $analysis,
        ]);
    }

    /**
     * Trigger a new AI log analysis.
     */
    public function analyze(Request $request)
    {
        $this->authorize('view ai log analysis');

        // Clear cache to force new analysis
        Cache::forget('ai_log_analysis_result');

        $analysis = $this->analysisService->analyzeRecentLogs();

        return response()->json([
            'status' => 'success',
            'analysis' => $analysis,
        ]);
    }

    /**
     * Clear the AI log analysis cache.
     */
    public function clear()
    {
        $this->authorize('view ai log analysis');

        Cache::forget('ai_log_analysis_result');

        return response()->json([
            'status' => 'success',
            'message' => 'Analysis cleared successfully',
        ]);
    }
}
