<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AutomationRule;
use App\Models\DeveloperCapacityLog;
use App\Models\Task;
use App\Models\TaskPrediction;
use App\Models\WorkflowRecommendation;
use App\Services\SmartWorkflowService;
use App\Traits\LogsActivity;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SmartWorkflowController extends Controller
{
    use LogsActivity;

    public function dashboard(SmartWorkflowService $service): View
    {
        $service->refreshDeveloperAvailability();

        return view('admin.workflow.dashboard', [
            'rules' => AutomationRule::latest()->get(),
            'capacity' => DeveloperCapacityLog::with('user')->whereDate('capacity_date', now()->toDateString())->orderByDesc('availability_score')->get(),
            'predictions' => TaskPrediction::with('task')->latest('predicted_at')->take(20)->get(),
            'recommendations' => WorkflowRecommendation::with(['task', 'user'])->latest()->take(20)->get(),
            'queueTasks' => Task::orderByDesc('automation_priority_score')->take(20)->get(),
        ]);
    }

    public function saveRule(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'rule_type' => 'required|in:auto_assign,delay_prediction,dependency_alert,smart_queue',
            'is_active' => 'nullable|boolean',
        ]);

        AutomationRule::create([
            ...$data,
            'conditions' => ['default' => true],
            'actions' => ['enabled' => true],
            'is_active' => (bool) ($data['is_active'] ?? true),
        ]);

        return back()->with('success', 'Automation rule created.');
    }

    public function runAutoAssign(SmartWorkflowService $service): RedirectResponse
    {
        $count = $service->autoAssignOpenTasks();
        $this->logActivity('auto_assign', 'workflow', 'Auto assignment executed', ['assigned' => $count]);
        return back()->with('success', "Auto assignment complete. {$count} task(s) assigned.");
    }

    public function runPredictions(SmartWorkflowService $service): RedirectResponse
    {
        $count = 0;
        foreach (Task::all() as $task) {
            $service->predictDelay($task);
            $count++;
        }

        $alerts = $service->generateDependencyAlerts();
        $this->logActivity('predict_delay', 'workflow', 'Delay predictions generated', ['tasks' => $count, 'alerts' => $alerts]);

        return back()->with('success', "Predictions generated for {$count} task(s). Dependency alerts: {$alerts}.");
    }

    public function runSmartQueue(SmartWorkflowService $service): RedirectResponse
    {
        $service->smartQueueTasks();
        $this->logActivity('smart_queue', 'workflow', 'Smart queue recalculated');
        return back()->with('success', 'Smart queue recalculated successfully.');
    }

    public function applyRecommendation(WorkflowRecommendation $recommendation): RedirectResponse
    {
        if ($recommendation->recommendation_type === 'assign_user' && $recommendation->task_id && $recommendation->recommended_user_id) {
            $recommendation->task?->assignees()->syncWithoutDetaching([$recommendation->recommended_user_id]);
            $recommendation->update(['is_applied' => true]);

            return back()->with('success', 'Recommendation applied and task assigned.');
        }

        $recommendation->update(['is_applied' => true]);
        return back()->with('success', 'Recommendation marked as applied.');
    }
}
