<?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
{
    /**
     * List all devices for the authenticated user
     */
    public function index(Request $request): JsonResponse
    {
        $devices = Device::where('user_id', $request->user()->id)
            ->orderByDesc('last_sync_at')
            ->get(['id', 'device_id', 'platform', 'model', 'os_version', 'app_version',
                   'last_sync_at', 'is_revoked', 'created_at']);

        return response()->json(['devices' => $devices]);
    }

    /**
     * Register or update a device (upsert).
     * Called by the Flutter app on each login / heartbeat.
     *
     * Body: { device_id, platform?, model?, os_version?, app_version?, fcm_token? }
     */
    public function register(Request $request): JsonResponse
    {
        $data = $request->validate([
            'device_id'   => 'required|string|max:255',
            'platform'    => 'nullable|string|max:50',
            'model'       => 'nullable|string|max:255',
            'os_version'  => 'nullable|string|max:100',
            'app_version' => 'nullable|string|max:100',
            'fcm_token'   => 'nullable|string|max:512',
        ]);

        $device = Device::updateOrCreate(
            ['device_id' => $data['device_id']],
            array_merge(['user_id' => $request->user()->id, 'is_revoked' => false], $data)
        );

        return response()->json(['device' => $device->only([
            'id', 'device_id', 'platform', 'model', 'is_revoked', 'created_at',
        ])], 201);
    }

    /**
     * Remove (unlink) a device from the account.
     * The device is deleted rather than revoked so it can re-register later.
     */
    public function remove(Request $request, string $deviceId): JsonResponse
    {
        Device::where('user_id', $request->user()->id)
            ->where('device_id', $deviceId)
            ->delete();

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

    /**
     * Revoke a device (remote logout) — existing Sanctum route
     */
    public function revoke(Request $request, string $deviceId): JsonResponse
    {
        $device = Device::where('user_id', $request->user()->id)
            ->where('device_id', $deviceId)
            ->firstOrFail();

        $device->update(['is_revoked' => true]);
        $request->user()->apiClientKeys()
            ->where('device_id', $deviceId)
            ->update(['is_active' => false, 'revoked_at' => now()]);

        // Revoke the Sanctum token for this device
        $request->user()->tokens()->where('name', 'device:' . $deviceId)->delete();

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