<?php

namespace App\Http\Controllers\Api\Messaging;

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

/**
 * Manages per-user messaging privacy preference.
 *
 * GET  /api/messages/settings  → return current setting
 * PATCH /api/messages/settings → update setting
 */
class MessagingSettingsController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $realtimeReady = (bool) config('messaging.realtime', false)
            && config('broadcasting.default') === 'reverb'
            && filled(config('broadcasting.connections.reverb.key'));

        return response()->json([
            'allow_messages_from' => $request->user()->allow_messages_from ?? 'everyone',
            'realtime_enabled' => $realtimeReady,
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $data = $request->validate([
            'allow_messages_from' => 'required|in:everyone,followers,mutual_followers,nobody',
        ]);

        $request->user()->update($data);

        return response()->json([
            'allow_messages_from' => $request->user()->allow_messages_from,
            'realtime_enabled' => (bool) config('messaging.realtime', false),
        ]);
    }
}
