<?php

namespace App\Services;

use App\Models\Article;
use App\Models\ArticlePublication;
use App\Models\Feed;
use App\Models\PlatformAccount;
use App\Models\PlatformChannel;
use App\Models\Route;
use App\Support\DateRange;

class DashboardStatsService
{
    /**
     * @return array<string, mixed>
     */
    public function getStats(DateRange $range): array
    {
        $bounds = [$range->from, $range->to];

        $articlesFetched = Article::query()
            ->whereBetween('created_at', $bounds)
            ->count();

        $articlesPublished = ArticlePublication::query()
            ->whereBetween('published_at', $bounds)
            ->count();

        $publishedPercentage = $articlesFetched > 0 ? round(($articlesPublished / $articlesFetched) * 100, 1) : 0.0;

        return [
            'articles_fetched' => $articlesFetched,
            'articles_published' => $articlesPublished,
            'published_percentage' => $publishedPercentage,
        ];
    }

    /**
     * @return array<string, int>
     */
    public function getSystemStats(): array
    {
        $totalFeeds = Feed::query()->count();
        $activeFeeds = Feed::query()->where('is_active', 1)->count();
        $totalPlatformAccounts = PlatformAccount::query()->count();
        $activePlatformAccounts = PlatformAccount::query()->where('is_active', 1)->count();
        $totalPlatformChannels = PlatformChannel::query()->count();
        $activePlatformChannels = PlatformChannel::query()->where('is_active', 1)->count();
        $totalRoutes = Route::query()->count();
        $activeRoutes = Route::query()->where('is_active', 1)->count();

        return [
            'total_feeds' => $totalFeeds,
            'active_feeds' => $activeFeeds,
            'total_platform_accounts' => $totalPlatformAccounts,
            'active_platform_accounts' => $activePlatformAccounts,
            'total_platform_channels' => $totalPlatformChannels,
            'active_platform_channels' => $activePlatformChannels,
            'total_routes' => $totalRoutes,
            'active_routes' => $activeRoutes,
        ];
    }
}
