<?php

namespace App\Http\Controllers\Api;

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

class DeviceController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        $request->validate([
            'device_id'   => 'required|string',
            'push_token'  => 'nullable|string',
            'platform'    => 'required|in:ios,android',
            'device_name' => 'nullable|string|max:255',
        ]);

        $device = Device::updateOrCreate(
            [
                'user_id'   => auth()->id(),
                'device_id' => $request->device_id,
            ],
            [
                'push_token'  => $request->push_token,
                'platform'    => $request->platform,
                'device_name' => $request->device_name,
                'active'      => true,
                'last_seen'   => now(),
            ]
        );

        // Dasselbe Push-Token bei anderen Usern deaktivieren
        if ($request->push_token) {
            Device::where('push_token', $request->push_token)
                ->where('user_id', '!=', auth()->id())
                ->update(['push_token' => null, 'active' => false]);
        }

        return response()->json([
            'success' => true,
            'data'    => $device,
        ], 201);
    }

    public function updateToken(Request $request): JsonResponse
    {
        $request->validate([
            'device_id'  => 'required|string',
            'push_token' => 'required|string',
        ]);

        Device::where('user_id', auth()->id())
            ->where('device_id', $request->device_id)
            ->update([
                'push_token' => $request->push_token,
                'active'     => true,
                'last_seen'  => now(),
            ]);

        return response()->json(['success' => true]);
    }

    public function deactivateToken(string $deviceId): JsonResponse
    {
        Device::where('user_id', auth()->id())
            ->where('device_id', $deviceId)
            ->update(['push_token' => null, 'active' => false]);

        return response()->json(['success' => true]);
    }

    public function destroy(Request $request, string $deviceId): JsonResponse
    {
        Device::where('user_id', auth()->id())
            ->where('device_id', $deviceId)
            ->delete();

        return response()->json([
            'success' => true,
            'message' => 'Gerät entfernt.',
        ]);
    }
}
