<?php
declare(strict_types=1);

namespace App\Modules\ParentApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\ApiErrorCodes;
use App\Shared\Services\PushNotificationService;

final class DeviceController extends ApiController
{
    public function register(Request $request): Response
    {
        $input = $request->jsonBody();
        $pushToken = trim((string) ($input['push_token'] ?? ''));
        $platform = trim((string) ($input['platform'] ?? ''));

        if ($pushToken === '' || !in_array($platform, ['ios', 'android'], true)) {
            return $this->errorResponse(
                'push_token و platform (ios/android) مطلوبان',
                422, [], ApiErrorCodes::VALIDATION_FAILED
            );
        }

        $bearerToken = $request->bearerToken();
        PushNotificationService::registerToken('parent', (int) App::getInstance()->currentParent()->id, $bearerToken, $pushToken, $platform);

        return $this->successResponse(['registered' => true]);
    }

    public function unregister(Request $request): Response
    {
        $bearerToken = $request->bearerToken();
        PushNotificationService::clearToken('parent', $bearerToken);

        return $this->successResponse(['unregistered' => true]);
    }
}
