<?php

declare(strict_types=1);

namespace App\Services\Auth;

use App\Models\User;
use App\Models\WorkspaceMembership;
use Illuminate\Support\Facades\Schema;

class PostLoginRedirectResolver
{
    public function resolve(User $user): string
    {
        $membershipQuery = WorkspaceMembership::query()->where('user_id', $user->getKey());

        $hasAnyActiveMembership = Schema::hasColumn('workspaces', 'archived_at')
            ? $membershipQuery
                ->join('workspaces', 'workspace_memberships.workspace_id', '=', 'workspaces.id')
                ->whereNull('workspaces.archived_at')
                ->exists()
            : $membershipQuery->exists();

        if (! $hasAnyActiveMembership) {
            return '/admin/no-access';
        }

        return '/admin';
    }
}
