<?php

namespace App\Http\Controllers;

use App\Http\Requests\DeviceTokenRequest;
use App\Models\DeviceToken;
use App\Notifications\TestNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class DeviceTokenController extends Controller
{
    public function store(DeviceTokenRequest $request): JsonResponse
    {
        $data = $request->validated();

        $deviceToken = DeviceToken::updateOrCreate(
            ['expo_push_token' => $data['expo_push_token']],
            [
                'platform' => $data['platform'] ?? null,
                'user_id' => $request->user()->getKey(),
            ],
        );

        return response()->json([
            'message' => $deviceToken->wasRecentlyCreated
                ? __('api.device_tokens.created')
                : __('api.device_tokens.updated'),
            'deviceToken' => [
                'id' => $deviceToken->id,
                'expoPushToken' => $deviceToken->expo_push_token,
                'platform' => $deviceToken->platform,
            ],
        ], $deviceToken->wasRecentlyCreated ? 201 : 200);
    }

    public function notifs(): JsonResponse
    {
        auth()->user()->notify(new TestNotification);

        return response()->json([
            'message' => __('api.device_tokens.notification_sent'),
        ]);

    }

    public function destroy(Request $request): Response
    {
        $data = $request->validate([
            'expo_push_token' => ['required', 'string', 'max:255'],
        ]);

        DeviceToken::query()
            ->where('user_id', $request->user()->getKey())
            ->where('expo_push_token', $data['expo_push_token'])
            ->delete();

        return response()->noContent();
    }
}
