<?php

namespace App\Http\Middleware;

use App\Models\UserNotification;
use App\Models\UserNotificationRead;
use App\Services\BrandingService;
use App\Services\LegalService;
use App\Services\UserPreferenceService;
use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that is loaded on the first page visit.
     *
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determine the current asset version.
     */
    public function version(Request $request): string|null
    {
        return parent::version($request);
    }

    /**
     * Define the props that are shared by default.
     *
     * @return array<string, mixed>
     */
    public function share(Request $request): array
    {
        $user = $request->user();

        return [
            ...parent::share($request),
            'auth' => [
                'user' => $user ? [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone,
                    'customer_tier' => $user->customer_tier ?? 'subscriber',
                    'status' => $user->status ?? 'active',
                    'has_transaction_pin' => method_exists($user, 'hasTransactionPin') ? $user->hasTransactionPin() : false,
                    'roles' => method_exists($user, 'getRoleNames') ? $user->getRoleNames()->values() : [],
                    'permissions' => method_exists($user, 'getAllPermissions')
                        ? $user->getAllPermissions()->pluck('name')->values()
                        : [],
                ] : null,
            ],
            'flash' => [
                'success' => fn () => $request->session()->get('success'),
                'error' => fn () => $request->session()->get('error'),
                'warning' => fn () => $request->session()->get('warning'),
                'purchase_result' => fn () => $request->session()->get('purchase_result'),
                'admin_api_secret_once' => fn () => $request->session()->get('admin_api_secret_once'),
            ],
            'configFlags' => [
                'services' => config('vtu.services.enabled', []),
            ],
            'notifications' => fn () => $this->notificationPayload($request),
            'branding' => fn () => app(BrandingService::class)->get(),
            'legal' => fn () => $this->legalPayload($request),
        ];
    }

    protected function notificationPayload(Request $request): array
    {
        $user = $request->user();

        if (! $user) {
            return [
                'unread_count' => 0,
                'latest_popup' => null,
            ];
        }

        $preferences = app(UserPreferenceService::class)->notificationPreferences($user);
        $inboxEnabled = (bool) ($preferences['inbox_enabled'] ?? true);
        $popupEnabled = (bool) ($preferences['popup_enabled'] ?? true);

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

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

        $applicable = $rows->filter(fn (UserNotification $row) => $row->appliesToUser($user->id));

        $unreadCount = $inboxEnabled
            ? $applicable
                ->filter(fn (UserNotification $row) => $row->show_in_inbox && blank(optional($reads->get($row->id))->read_at))
                ->count()
            : 0;

        $popup = $popupEnabled
            ? $applicable
                ->first(function (UserNotification $row) use ($reads) {
                    $read = $reads->get($row->id);

                    return $row->show_popup && blank(optional($read)->dismissed_popup_at);
                })
            : null;

        return [
            'unread_count' => $unreadCount,
            'latest_popup' => $popup ? [
                'id' => $popup->id,
                'title' => $popup->title,
                'message' => $popup->message,
                'created_at' => optional($popup->created_at)->toDateTimeString(),
            ] : null,
        ];
    }

    protected function legalPayload(Request $request): array
    {
        $legal = app(LegalService::class)->get();
        $user = $request->user();
        $version = (int) ($legal['terms_version'] ?? 1);
        $acceptedVersion = (int) ($user?->terms_accepted_version ?? 0);

        return [
            'terms_title' => (string) ($legal['terms_title'] ?? 'Terms and Conditions'),
            'terms_content' => (string) ($legal['terms_content'] ?? ''),
            'terms_version' => $version,
            'must_acknowledge' => $user ? $acceptedVersion < $version : false,
            'accepted_version' => $acceptedVersion,
        ];
    }
}
