<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Shared\Models\DeviceToken;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

        $user = $request->user();

        DeviceToken::withoutGlobalScope('academy')->updateOrCreate(
            ['device_token' => $request->token],
            [
                'academy_id' => $user->academy_id,
                'user_id' => $user->id,
                'platform' => $request->platform,
                'device_name' => $request->device_name,
                'app_version' => $request->app_version,
                'is_active' => true,
                'last_used_at' => now(),
            ]
        );

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

    public function refresh(Request $request): JsonResponse
    {
        $request->validate([
            'old_token' => 'required|string|max:255',
            'new_token' => 'required|string|max:255',
        ]);

        $device = DeviceToken::withoutGlobalScope('academy')
            ->where('device_token', $request->old_token)
            ->where('user_id', $request->user()->id)
            ->first();

        if ($device) {
            $device->update([
                'device_token' => $request->new_token,
                'last_used_at' => now(),
            ]);
        } else {
            return response()->json([
                'error' => 'device_not_found',
                'message' => 'الجهاز غير مسجل',
            ], 404);
        }

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

    public function destroy(string $token, Request $request): JsonResponse
    {
        DeviceToken::withoutGlobalScope('academy')
            ->where('device_token', $token)
            ->where('user_id', $request->user()->id)
            ->delete();

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