<?php

namespace App\Http\Controllers\Shop;

use App\Http\Controllers\Controller;
use App\Models\UserNotification;
use App\Models\UserNotificationRead;
use App\Services\UserPreferenceService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class NotificationController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user();
        $preferences = app(UserPreferenceService::class)->notificationPreferences($user);
        $inboxEnabled = (bool) ($preferences['inbox_enabled'] ?? true);

        if (! $inboxEnabled) {
            return Inertia::render('App/Notifications/Index', [
                'notifications' => [],
                'inboxEnabled' => false,
            ]);
        }

        $rows = UserNotification::query()
            ->where('is_active', true)
            ->where('show_in_inbox', true)
            ->latest('id')
            ->limit(200)
            ->get();

        $reads = UserNotificationRead::query()
            ->where('user_id', $user->id)
            ->whereIn('user_notification_id', $rows->pluck('id'))
            ->get()
            ->keyBy('user_notification_id');

        $notifications = $rows
            ->filter(fn (UserNotification $row) => $row->appliesToUser($user->id))
            ->values()
            ->map(function (UserNotification $row) use ($reads) {
                $read = $reads->get($row->id);

                return [
                    'id' => $row->id,
                    'title' => $row->title,
                    'message' => $row->message,
                    'created_at' => optional($row->created_at)->toDateTimeString(),
                    'read_at' => optional($read?->read_at)->toDateTimeString(),
                ];
            });

        return Inertia::render('App/Notifications/Index', [
            'notifications' => $notifications,
            'inboxEnabled' => true,
        ]);
    }

    public function read(Request $request, UserNotification $notification): RedirectResponse
    {
        $user = $request->user();

        if (! $notification->appliesToUser($user->id)) {
            abort(404);
        }

        UserNotificationRead::query()->updateOrCreate(
            [
                'user_notification_id' => $notification->id,
                'user_id' => $user->id,
            ],
            [
                'read_at' => now(),
            ]
        );

        return back()->with('success', 'Notification marked as read.');
    }

    public function dismissPopup(Request $request, UserNotification $notification): RedirectResponse
    {
        $user = $request->user();

        if (! $notification->appliesToUser($user->id)) {
            abort(404);
        }

        UserNotificationRead::query()->updateOrCreate(
            [
                'user_notification_id' => $notification->id,
                'user_id' => $user->id,
            ],
            [
                'dismissed_popup_at' => now(),
            ]
        );

        return back();
    }
}
