<?php

namespace App\Http\Controllers\Api\Customer;

use App\Http\Controllers\Controller;
use App\Models\FcmToken;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DeviceTokenController extends Controller
{
    /** POST /customer/device-tokens — register/refresh this device's push token. */
    public function store(Request $request): JsonResponse
    {
        $data = $request->validate([
            'token'    => 'required|string|max:512',
            'platform' => 'nullable|in:android,ios,web',
        ]);

        $user = Auth::guard('customer')->user();

        FcmToken::updateOrCreate(
            ['token' => $data['token']],
            [
                'tokenable_type' => User::class,
                'tokenable_id'   => $user->id,
                'platform'       => $data['platform'] ?? 'android',
                'last_used_at'   => now(),
            ],
        );

        return response()->json(['message' => 'Device registered for notifications.']);
    }

    /** DELETE /customer/device-tokens — drop this device's token (on logout). */
    public function destroy(Request $request): JsonResponse
    {
        $request->validate(['token' => 'required|string']);
        FcmToken::where('token', $request->token)->delete();

        return response()->json(['message' => 'Device unregistered.']);
    }
}
