<?php

namespace EasyLinkAutomations\HTTP\Controllers;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\Config;
use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;
use EasyLinkAutomations\Models\Automation;
use EasyLinkAutomations\Models\Connection;
use EasyLinkAutomations\Models\ExecutionLog;

/**
 * Provides dashboard overview data.
 */
final class DashboardController
{
    public function index(Request $request): Response
    {
        $activityPage    = max(1, (int) ($request->get('activity_page') ?? 1));
        $activityPerPage = max(1, min(100, (int) ($request->get('activity_per_page') ?? 10)));

        $totalAutomations  = Automation::count();
        $activeAutomations = Automation::count('active');
        $executionsToday   = ExecutionLog::countToday();
        $totalExecutions   = ExecutionLog::countAll();
        $activeConnections = Connection::count('active');
        $activity          = ExecutionLog::paginate($activityPage, $activityPerPage);
        $recentAutomations = Automation::paginate(1, 5)['items'];

        return Response::success([
            'version' => Config::VERSION,
            'stats'   => [
                'total_automations'  => $totalAutomations,
                'active_automations' => $activeAutomations,
                'executions_today'   => $executionsToday,
                'total_executions'   => $totalExecutions,
                'active_connections' => $activeConnections,
            ],
            'recent_automations' => $recentAutomations,
            'recent_activity'    => $activity,
        ]);
    }
}
