<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Registers/unregisters push tokens for whichever model a Sanctum token
 * belongs to (User — staff/driver app, or Customer — passenger app), so the
 * same two endpoints serve both mobile apps.
 */
class DeviceTokenController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'token' => ['required', 'string', 'max:500'],
            'platform' => ['nullable', 'in:ios,android,web'],
        ]);

        $request->user()->deviceTokens()->updateOrCreate(
            ['token' => $data['token']],
            ['platform' => $data['platform'] ?? null, 'is_active' => true]
        );

        return response()->json(['message' => __('api.device_token_registered')], 201);
    }

    public function destroy(Request $request): JsonResponse
    {
        $data = $request->validate(['token' => ['required', 'string']]);

        $request->user()->deviceTokens()->where('token', $data['token'])->update(['is_active' => false]);

        return response()->json(['message' => __('api.device_token_unregistered')]);
    }
}
