<?php declare(strict_types=1);

namespace App\Services\CaptchaToken;

use App\Contracts\GenerateTokenCommand;
use App\Models\CaptchaToken;
use App\Models\User;

final readonly class CaptchaTokenHandler
{
    public function __construct(
        private GenerateTokenCommand $generatePublicTokenCommand,
        private GenerateTokenCommand $generatePrivateTokenCommand
    ) { }

    public function handleStore(array $data, User $user): CaptchaToken
    {
        $captchaToken = new CaptchaToken();
        $captchaToken->public_token = $this->generatePublicTokenCommand->unique(CaptchaToken::query(), 'public_token');
        $captchaToken->private_token = $this->generatePrivateTokenCommand->unique(CaptchaToken::query(), 'private_token');
        $captchaToken->user_id = $user->id;
        $captchaToken->fill($data)->save();

        return $captchaToken;
    }

    public function handleUpdate(CaptchaToken $captchaToken, array $data): CaptchaToken
    {
        $captchaToken->update($data);
        $captchaToken->touch();

        return $captchaToken;
    }

    public function handleDestroy(CaptchaToken $captchaToken): void
    {
        $captchaToken->delete();
    }
}
