<?php

namespace App\Support;

use App\Models\AccessType;
use App\Models\User;
use App\Models\UserAccess;

class CrmAccess
{
    public static function accessibleUserIds(User $user): array
    {
        if ((int) $user->is_admin === 1) {
            return User::where('business_id', $user->business_id)->pluck('id')->map(fn ($id) => (int) $id)->all();
        }

        $access = UserAccess::where('user_id', $user->id)->first();
        $accessTypeId = (int) ($access?->access_type_id ?: AccessType::PRIVATE);

        if ($accessTypeId === AccessType::PUBLIC) {
            return User::where('business_id', $user->business_id)->pluck('id')->map(fn ($id) => (int) $id)->all();
        }

        $ids = collect([(int) $user->id]);

        if ($accessTypeId === AccessType::SPECIFIC_USERS) {
            $ids = $ids->merge(
                UserAccess::where('user_id', $user->id)
                    ->whereNotNull('specific_user_id')
                    ->pluck('specific_user_id')
            );
        }

        return $ids->map(fn ($id) => (int) $id)->unique()->values()->all();
    }

    public static function canAccessOwner(User $user, ?int $ownerId): bool
    {
        return $ownerId !== null && in_array((int) $ownerId, self::accessibleUserIds($user), true);
    }
}
