<?php

namespace App\Services;

use App\Models\AuditLog; // Assume we create this or use DB
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class AIOperatorService
{
    /**
     * The AI Modes:
     * - assistant: Suggest only
     * - manager: Automatic creation of low-risk items (tasks)
     * - admin: Full system control (requires confirmation for critical items)
     */
    protected $mode = 'assistant';

    public function __construct($mode = 'assistant')
    {
        $this->mode = $mode;
    }

    /**
     * Execute a system action requested by the AI.
     */
    public function executeAction(array $actionData)
    {
        $action = $actionData['action'];
        $payload = $actionData['payload'];
        $confidence = $actionData['confidence'] ?? 0;

        // 1. Permission & Mode Check
        if (!$this->canExecute($action, $confidence)) {
            return [
                'status' => 'pending_confirmation',
                'message' => "I need your confirmation to execute: " . $action,
                'action_data' => $actionData
            ];
        }

        // 2. Execution Logic
        return DB::transaction(function () use ($action, $payload) {
            $result = $this->runInternalAction($action, $payload);
            
            // 3. Audit Logging (Critical for Senior Grade)
            $this->logAction($action, $payload, $result);

            return [
                'status' => 'success',
                'message' => "Successfully executed: " . $action,
                'data' => $result
            ];
        });
    }

    protected function canExecute($action, $confidence)
    {
        if ($this->mode === 'admin') return true;
        if ($this->mode === 'manager' && $action === 'create_task' && $confidence > 0.9) return true;
        
        return false;
    }

    protected function runInternalAction($action, $payload)
    {
        switch ($action) {
            case 'create_task':
                return DB::table('tasks')->insertGetId(array_merge($payload, [
                    'created_at' => now(),
                    'updated_at' => now(),
                ]));
            
            case 'update_deal':
                return DB::table('deals')
                    ->where('id', $payload['id'])
                    ->update($payload['data']);

            default:
                throw new \Exception("Unsupported AI action: " . $action);
        }
    }

    protected function logAction($action, $payload, $result)
    {
        DB::table('ai_audit_logs')->insert([
            'user_id' => Auth::id(),
            'action_type' => $action,
            'reasoning' => 'AI detected high-confidence intent',
            'input_payload' => json_encode($payload),
            'output_payload' => json_encode($result),
            'confidence' => 0.95,
            'mode' => $this->mode,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
