<?php declare(strict_types=1);

namespace App\Services\Private;

use App\Enums\CaptchaLogType;
use App\Models\CaptchaToken;
use App\Models\User;
use App\Repositories\CaptchaLogRepository;
use App\ServiceResults\Private\Dashboard\ChartCaptchaActivity;
use App\ServiceResults\ServiceResultArray;
use App\ServiceResults\ServiceResultError;
use App\Services\Service;
use Illuminate\Support\Carbon;

final class DashboardService extends Service
{
    public function __construct(
        private readonly CaptchaLogRepository $captchaLogRepository,
    ) { }

    public function captchaLog(User $user, int $limit = 10, array $with = []): ServiceResultError | ServiceResultArray
    {
        if ($user->cannot('viewAny', CaptchaToken::class)) {
            return $this->result([
               'items' => collect([]),
               'user'  => $user,
            ]);
        }

        return $this->result([
            'items' => $this->captchaLogRepository->getCaptchaLogs($with)->get($limit),
            'user'  => $user,
        ]);
    }

    public function chartCaptchaActivity(User $user, Carbon $from, Carbon $to): ServiceResultError | ChartCaptchaActivity
    {
        if ($user->cannot('viewAny', CaptchaToken::class)) {
            return $this->errFobidden(__('Access is denied'));
        }

        if ($to < $from) {
            return $this->errValidate(__('From cannot be greater than To'));
        }

        $quantity = $this->captchaLogRepository->countByDays($from, $to);

        return new ChartCaptchaActivity(
            from: $from,
            to:   $to,
            quantityByDays: $quantity,
        );
    }
}
