<?php

namespace App\Http\Controllers\Admin\Dashboard;

use App\Filters\Application\Dashboard\DashboardOverviewFilter;
use App\Http\Controllers\Controller;
use App\Models\Application\AI\Completion;
use App\Models\Core\Auth\User;
use App\Models\Core\Status;
use App\Models\Application\AI\Document;
use App\Services\Application\Dashboard\DashboardService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use JetBrains\PhpStorm\ArrayShape;

class AppDashboardController extends Controller
{
    public $status;

    public function __construct()
    {
        $this->status = $this->getUserStatus();
    }

    #[ArrayShape(['total_user' => "int", 'total_active' => "int", 'total_de_active' => "int", 'total_invited' => "int"])] public function userCard(): array
    {
        $totalUser = $this->userCount();
        $totalActive = $this->userCount($this->status['status_active']);
        $totalDeactive = $this->userCount($this->status['status_inactive']);
        $totalInvited = $this->userCount($this->status['status_invited']);

        return [
            'total_user' => $totalUser,
            'total_active' => $totalActive,
            'total_de_active' => $totalDeactive,
            'total_invited' => $totalInvited
        ];
    }

    private function userCount($status = null): int
    {
        return User::query()
            ->when($status, fn (Builder $builder) => $builder->where('status_id', $status))
            ->count();
    }

    private function getUserStatus()
    {
        return Status::where('type', 'user')
            ->pluck('id', 'name');
    }


    public function topDocumenter(): array
    {
        $topThreetopDocumenters = Document::query()->groupBy('user_id')
            ->select('user_id', DB::raw('count(*) as documents'))
            ->with('user:id,first_name,last_name,uuid')
            ->limit(3)
            ->get();

        $threeDocumenterName = [];
        $threeDocumenterValue = [];
        foreach ($topThreetopDocumenters as $value) {
            $threeDocumenterName[] = $value->user->full_name;
            $threeDocumenterValue[] = $value->documents;
        }

        return [
            'labels' => $threeDocumenterName,
            'documents' => $threeDocumenterValue,
        ];
    }
    public function topTokenConsumer(): array
    {
        $topThreeConsumer = Completion::query()->groupBy('user_id')
            ->select('user_id', DB::raw('sum(total_tokens) as consumed'))
            ->with('user:id,first_name,last_name,uuid')
            ->limit(3)
            ->get();

        $threeConsumerName = [];
        $threeConsumerValue = [];
        foreach ($topThreeConsumer as $value) {
            $threeConsumerName[] = $value->user->full_name;
            $threeConsumerValue[] = $value->consumed;
        }

        return [
            'labels' => $threeConsumerName,
            'consumers' => $threeConsumerValue,
        ];
    }


    public function completionOverview(): array
    {
        $filter = resolve(DashboardOverviewFilter::class);
        $completionQuery = Completion::filters($filter);

        if (!auth()->user()->isAdmin()) $completionQuery->where('user_id', auth()->id());

        $service = resolve(DashboardService::class);
        return $service->completionOverview($completionQuery);
    }

    public function documentOverview(): array
    {
        $filter = resolve(DashboardOverviewFilter::class);
        $documentQuery = Document::filters($filter);

        if (!auth()->user()->isAdmin()) $documentQuery->where('user_id', auth()->id());

        $completionQuery = Completion::filters($filter);

        if (!auth()->user()->isAdmin()) $completionQuery->where('user_id', auth()->id());

        $service = resolve(DashboardService::class);

        $document = $service->documentOverview($documentQuery);

        $completion = $service->completionCountOverview($completionQuery);
        $document['document_overview'] = array_merge($document['document_overview'], $completion['completion_overview']);

        $document['total_completions'] = $completion['total_completions'];
        return $document;
    }
}
