<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\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('coach', (int) App::getInstance()->currentCoach()->id, $bearerToken, $pushToken, $platform);

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

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

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