<?php declare(strict_types=1);

namespace App\Http\Controllers\Private;

use App\Http\Resources\Private\Dashboard\ChartCaptchaActivity;
use App\Services\Private\DashboardService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

final class DashboardController extends Controller
{
    public function __construct(
        private readonly DashboardService $dashboardService,
    ) { }

    public function index(Request $request): View
    {
        $user = $request->user();
        $limit = 30;
        $with = ['captcha', 'captcha.captchaToken'];
        $result = $this->dashboardService->captchaLog($user, $limit, $with);
        if ($result->isError()) {
            $this->errors($result);
        }

        return view('private/dashboard/index', $result->getData());
    }

    public function chartCaptchaActivity(Request $request): JsonResponse
    {
        $user = $request->user();
        $from = Carbon::now()->subDays(7);
        $to = Carbon::now();
        $result = $this->dashboardService->chartCaptchaActivity($user, $from, $to);
        if (!$result->isSuccess()) {
            return response()->json($result->getData())->setStatusCode($result->getCode());
        }

        return response()->json(new ChartCaptchaActivity($result));
    }
}
