<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

/**
 * Mobile device registration for push notifications.
 *
 * Flutter calls POST /devices right after sign-in (or after FCM token
 * refresh) so the backend knows where to deliver notifications. It calls
 * DELETE /devices on sign-out so the token is no longer addressable.
 *
 * Token uniqueness is enforced at the DB level (unique index on `token`),
 * so re-registration is an upsert keyed by token — same install on a new
 * user simply rebinds the row.
 */
class DevicesController extends Controller
{
    /**
     * POST /api/v1/mobile/devices
     *
     * Body:
     *   token: string (required)        — FCM registration token / APNs device token
     *   platform: android|ios|web       — defaults to android
     *   app_version: string             — optional, for analytics + targeting old clients
     *   device_name: string             — optional, e.g. "Pixel 8"
     *   locale: string                  — optional, e.g. "fr-FR" — used to localize push body
     */
    public function store(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'token'       => 'required|string|max:512',
            'platform'    => 'nullable|in:android,ios,web',
            'app_version' => 'nullable|string|max:32',
            'device_name' => 'nullable|string|max:128',
            'locale'      => 'nullable|string|max:8',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors'  => $validator->errors(),
            ], 422);
        }

        $user = $request->user();
        $now = now();

        $payload = [
            'user_id'      => $user->id,
            'workspace_id' => $user->active_workspace_id,
            'platform'     => $request->input('platform', 'android'),
            'app_version'  => $request->input('app_version'),
            'device_name'  => $request->input('device_name'),
            'locale'       => $request->input('locale'),
            'last_seen_at' => $now,
            'updated_at'   => $now,
        ];

        // upsert by unique `token` — handles both first registration and
        // FCM token-refresh callbacks where the same install hands us a
        // new token.
        DB::table('device_tokens')->updateOrInsert(
            ['token' => $request->string('token')],
            array_merge($payload, ['created_at' => $now])
        );

        return response()->json([
            'success' => true,
            'message' => 'Device registered.',
        ]);
    }

    /**
     * DELETE /api/v1/mobile/devices
     *
     * Body: token (required) — must belong to the authenticated user.
     */
    public function destroy(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'token' => 'required|string|max:512',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'errors'  => $validator->errors(),
            ], 422);
        }

        DB::table('device_tokens')
            ->where('token', $request->string('token'))
            ->where('user_id', $request->user()->id)
            ->delete();

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