<?php

namespace App\Http\Middleware;

use Inertia\Inertia;
use App\Utils\Helper;
use App\Enums\UserType;
use App\Models\Company;
use Inertia\Middleware;
use App\Models\Department;
use Tightenco\Ziggy\Ziggy;
use App\Models\Notification;
use Illuminate\Http\Request;

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
  {
    if (str(env('APP_URL'))->startsWith('https://')) {
      Inertia::encryptHistory(true);
    }
    $lang = Helper::getLangActive($request);

    $company = Company::active($request)->select('id', 'name', 'code')->first();
    $department = Department::active($request)->select('id', 'name', 'code', 'is_finance')->first();

    $userRole = auth()->check() ? auth()->user()->role : null;
    $notifications = [];
    $notificationCount = 0;

    if (auth()->check()) {
      $notifications = Notification::select('id', 'title', 'message', 'is_read', 'created_at')->where('user_id', auth()->id())->orderBy('is_read')->orderBy('created_at', 'desc')->limit(5)->get();
      $notificationCount = Notification::where('user_id', auth()->id())->where('is_read', false)->count();
    }

    return array_merge(parent::share($request), [
      'appName' => config('app.name'),
      'appUrl' => config('app.url'),
      'auth' => [
        'user' => $request->user(),
        'has_password' => isset($request->user()?->password),
      ],
      'ziggy' => function () use ($request) {
        $ziggy = (new Ziggy)->toArray();
        unset($ziggy['routes']);
        return array_merge($ziggy, [
          'location' => $request->url(),
          'query' => count($request->query()) == 0 ? null : $request->query()
        ]);
      },
      'flash' => [
        'message' => fn() => $request->session()->get('message'),
        'success' => fn() => $request->session()->get('success'),
        'error' => fn() => $request->session()->get('error'),
      ],
      'location' => $request->fullUrl(),
      'locale' => $lang,
      'active_session' => [
        'company' => $company,
        'department' => $department,
      ],
      'nav_meta' => [
        'notifications' => $notifications,
        'notification_count' => $notificationCount,
      ],
      'isManager' => $userRole == UserType::Manager,
      'isDirector' => $userRole == UserType::Director,
    ]);
  }
}
