<?php

namespace App\Http\Controllers\Api\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Event;
use App\Models\TenantFeedback;
use App\Models\User;
use App\Notifications\TenantFeedbackSubmitted;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
use Illuminate\Validation\Rule;

class TenantFeedbackController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $tenantId = $request->attributes->get('tenant_id');

        if (! $tenantId) {
            abort(403, 'Unauthorised');
        }

        $validated = $request->validate([
            'category' => ['required', 'string', 'max:80'],
            'sentiment' => ['nullable', 'string', Rule::in(['positive', 'neutral', 'negative'])],
            'rating' => ['nullable', 'integer', 'min:1', 'max:5'],
            'title' => ['nullable', 'string', 'max:120'],
            'message' => ['nullable', 'string', 'max:2000'],
            'event_slug' => ['nullable', 'string', 'max:255'],
            'metadata' => ['nullable', 'array'],
        ]);

        $eventId = null;
        if (! empty($validated['event_slug'])) {
            $eventSlug = $validated['event_slug'];
            $event = Event::query()
                ->where('slug', $eventSlug)
                ->where('tenant_id', $tenantId)
                ->select('id')
                ->first();

            $eventId = $event?->id;
        }

        $feedback = TenantFeedback::create([
            'tenant_id' => $tenantId,
            'event_id' => $eventId,
            'category' => $validated['category'],
            'sentiment' => $validated['sentiment'] ?? null,
            'rating' => $validated['rating'] ?? null,
            'title' => $validated['title'] ?? null,
            'message' => $validated['message'] ?? null,
            'metadata' => $validated['metadata'] ?? null,
        ]);

        $recipients = User::query()
            ->whereIn('role', ['super_admin', 'superadmin'])
            ->whereNotNull('email')
            ->get();

        if ($recipients->isNotEmpty()) {
            Notification::send($recipients, new TenantFeedbackSubmitted($feedback));
        }

        return response()->json([
            'message' => 'Feedback gespeichert',
            'data' => [
                'id' => $feedback->id,
                'created_at' => $feedback->created_at?->toIso8601String(),
            ],
        ], 201);
    }
}
