<?php

namespace App\Http\Controllers\Api\V1;

use App\Enums\UserRole;
use App\Http\Controllers\Controller;
use App\Http\Requests\NotificationPreferenceRequest;
use App\Models\NotificationPreference;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class NotificationPreferenceController extends Controller
{
    use ApiResponse;

    public function show(Request $request)
    {
        return $this->success($this->preferenceFor($request));
    }

    public function update(NotificationPreferenceRequest $request)
    {
        $preference = $this->preferenceFor($request);
        $data = $request->validated();

        if (array_key_exists('consent', $data)) {
            $data['consent_at'] = $data['consent'] ? now() : null;
            unset($data['consent']);
        }

        $preference->update($data);

        return $this->success($preference->fresh(), 'Notification preferences updated.');
    }

    private function preferenceFor(Request $request): NotificationPreference
    {
        $user = $request->user();
        $patientId = $user->role === UserRole::PATIENT ? $user->patient?->id : null;

        return NotificationPreference::query()->firstOrCreate(
            [
                'organization_id' => $user->organization_id,
                $patientId ? 'patient_id' : 'user_id' => $patientId ?: $user->id,
            ],
            [
                'user_id' => $patientId ? $user->id : $user->id,
                'patient_id' => $patientId,
                'push_enabled' => true,
                'whatsapp_enabled' => true,
                'email_enabled' => true,
                'in_app_enabled' => true,
            ]
        );
    }
}
