<?php

namespace App\Support;

use Illuminate\Contracts\Auth\Authenticatable;

class PostLoginRedirect
{
    /**
     * Pick the first route the user can access safely.
     */
    public static function routeFor(?Authenticatable $user): string
    {
        if (!$user) {
            return 'dashboard';
        }

        $candidates = [
            'dashboard.view'           => 'dashboard',
            'sales.view'               => 'sales.index',
            'purchases.view'           => 'purchases.index',
            'expenses.view'            => 'expenses.index',
            'bank-withdrawals.view'    => 'bank-withdrawals.index',
            'employees.view'           => 'employees.index',
            'rosters.view'             => 'rosters.index',
            'employee-payments.view'   => 'employee-payments.index',
            'customers.view'           => 'customers.index',
            'customer-ledgers.view'    => 'customer-ledgers.index',
            'vendors.view'             => 'vendors.index',
            'shareholders.view'        => 'shareholders.index',
            'items.view'               => 'items.index',
            'currencies.view'          => 'currencies.index',
            'sale-sources.view'        => 'settings.sale-sources.index',
            'expense-categories.view'  => 'settings.expense-categories.index',
            'reports.view'             => 'reports.daily',
            'shareholder-reports.view' => 'reports.shareholders',
            'users.view'               => 'users.index',
            'roles.view'               => 'roles.index',
        ];

        foreach ($candidates as $permission => $routeName) {
            if (method_exists($user, 'can') && $user->can($permission)) {
                return $routeName;
            }
        }

        // Always available for authenticated users.
        return 'profile.edit';
    }
}
