<?php
/**
 * Route for department self-serve vehicle conditions
 */

namespace routes;

use classes\authentication;
use classes\response;
use classes\selfserve;
use modules\selfserve\classes\selfserve_wash_flow;
use modules\subusers\helpers\subusers_permission_node_key;
use objects\customer_vehicles_o;
use objects\department_lanes_o;
use objects\department_selfserve_tasks_o;
use objects\department_selfserve_vehicle_conditions_o;
use objects\departments_o;
use objects\logs_o;
use objects\selfserve_wash_sessions_o;
use traits\route_t;

class departmentSelfserveVehicleConditionsRoute
{
    use route_t;

    public function run(): void
    {
        /**
         * List department self-serve vehicle conditions
         */
        $this->get('/department/selfserve/vehicle/conditions', function () {
            global $response;
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $has_global = $user->hasPermission('list_department_selfserve_vehicle_conditions');
            $has_own = $user->hasPermission('list_own_department_selfserve_vehicle_conditions');

            if (!$has_global && !$has_own) {
                $response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
            }

            (new logs_o())->add('department_selfserve_vehicle_conditions', 'global', 1, $user->id, 'LIST_VEHICLE_CONDITIONS', 'User listed department self-serve vehicle conditions');

            $conditions_o = new department_selfserve_vehicle_conditions_o();
            $customer_number = (int)$user->customer_number->value();

            if (self::isParametersSet(['id'])) {
                $conditions_o->select((int)self::getParameter('id'));
                if ($conditions_o->exists()) {
                    if ($has_global) {
                        $authorized_department_ids = $user->getGroup()->getDepartments();
                        if (!in_array((int)$conditions_o->department->value(), $authorized_department_ids, true)) {
                            $this->forbidDepartmentAccess((int)$conditions_o->department->value());
                        }
                    } else {
                        if ((int)$conditions_o->customer_id->value() !== $customer_number) {
                            $response->forbidden(['list_department_selfserve_vehicle_conditions']);
                        }
                    }
                    $response->success($conditions_o->asArray());
                } else {
                    $response->error('Condition not found', 404);
                }
            }

            $filters = [];
            if ($has_global) {
                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (self::isParametersSet(['department'])) {
                    $requested_department = (int)self::getParameter('department');
                    if (!in_array($requested_department, $authorized_department_ids, true)) {
                        $this->forbidDepartmentAccess($requested_department);
                    }
                    $filters['department'] = $requested_department;
                } else {
                    $filters['department'] = $authorized_department_ids;
                }

                if (self::isParametersSet(['customer_id'])) {
                    $filters['customer_id'] = (int)self::getParameter('customer_id');
                }
            } else {
                $filters['customer_id'] = $customer_number;
                if (self::isParametersSet(['department'])) {
                    $filters['department'] = (int)self::getParameter('department');
                }
            }

            if (self::isParametersSet(['lane'])) {
                $filters['lane'] = (int)self::getParameter('lane');
            }

            if (self::isParametersSet(['reg'])) {
                $filters['reg'] = selfserve::standardize_registration((string)self::getParameter('reg'));
            }

            if (self::isParametersSet(['question'])) {
                $filters['question'] = (int)self::getParameter('question');
            }

            $response->success(
                $conditions_o->setSearchableFields(['id', 'department', 'lane', 'customer_id', 'reg', 'question', 'value', 'created_at', 'updated_at', 'deleted_at'])
                    ->listObjectsWithPaginationIfSet(function ($condition) {
                        $c = new department_selfserve_vehicle_conditions_o();
                        $c->select((int)$condition['id']);
                        return $c->asArray();
                    }, $conditions_o->forceRestrictFilters($filters))
            );
        }, [
            'list_department_selfserve_vehicle_conditions' => 'List all department self-serve vehicle conditions',
            'list_own_department_selfserve_vehicle_conditions' => 'List own department self-serve vehicle conditions'
        ]);

        /**
         * Check whether self-serve is allowed for a specific vehicle and lane
         */
        $this->get('/department/selfserve/vehicle/allowed', function () {
            global $response;
            [$user, $actor_id, $subuser_id] = $this->getAuthenticatedSelfServePrincipal();
            $own_permission = self::definePermission('list_own_department_selfserve_vehicle_conditions', subusers_permission_node_key::SELFSERVE_LIST);

            $customer_number_context = $this->resolveEffectiveCustomerNumber();
            $has_global = $user !== null && $this->hasPermission('list_department_selfserve_vehicle_conditions');
            $has_own = $this->hasPermission($own_permission, $customer_number_context);
            if (!$has_global && !$has_own) {
                $response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
            }

            if ($user === null && !$has_own) {
                $response->error('Invalid session', 400);
            }

            self::requireParameters(['lane_id', 'reg']);
            $lane_id = (int)self::getParameter('lane_id');
            $reg = selfserve::standardize_registration((string)self::getParameter('reg'));

            $lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);
            $customer_number = null;
            if ($has_own && (!$has_global || !$this->userHasLaneDepartmentAccess($user, $lane))) {
                $customer_number = $this->requireAuthenticatedCustomerNumber($user, 'list_department_selfserve_vehicle_conditions');
            }
            $vehicle_type_id = $this->resolveVehicleTypeIdFromQuery();
            $flow = $this->getWashFlow();

            if ($vehicle_type_id !== null) {
                $flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [
                    'create_session' => false,
                    'subuser_id' => $subuser_id,
                ]);
            }

            (new logs_o())->add('department_selfserve_vehicle_conditions', (int)$lane->department->value(), 1, $actor_id, 'CHECK_VEHICLE_ALLOWED', 'User checked self-serve eligibility for lane ' . $lane_id . ' and vehicle ' . $reg);
            $response->success($flow->previewVehicleEligibility($lane_id, $reg, $customer_number, $vehicle_type_id, [
                'subuser_id' => $subuser_id,
            ]));
        }, [
            'list_department_selfserve_vehicle_conditions' => 'Check whether self-serve is allowed for a specific vehicle',
            'list_own_department_selfserve_vehicle_conditions' => 'Check whether self-serve is allowed for a customer-scoped vehicle'
        ]);

        /**
         * Get self-serve wash summary
         */
        $this->get('/department/selfserve/washes/summary', function () {
            global $response;
            [$user, $_actor_id, $subuser_id] = $this->getAuthenticatedSelfServePrincipal();
            $own_permission = self::definePermission('list_own_department_selfserve_vehicle_conditions', subusers_permission_node_key::SELFSERVE_LIST);

            $customer_number_context = $this->resolveEffectiveCustomerNumber();
            $has_global = $user !== null && $this->hasPermission('list_department_selfserve_vehicle_conditions');
            $has_own = $this->hasPermission($own_permission, $customer_number_context);
            if (!$has_global && !$has_own) {
                $response->forbidden(['list_department_selfserve_vehicle_conditions', 'list_own_department_selfserve_vehicle_conditions']);
            }

            if ($user === null && !$has_own) {
                $response->error('Invalid session', 400);
            }

            $flow = $this->getWashFlow();
            $vehicle_type_id = $this->resolveVehicleTypeIdFromQuery();
            try {
                if (self::isParametersSet(['session_id'])) {
                    $summary = $flow->getSessionSummary((int)self::getParameter('session_id'));
                    $this->assertSummaryAccess($user, $summary, $has_global, $has_own, 'list_department_selfserve_vehicle_conditions');

                    if ($this->shouldRefreshSummaryForVehicleType($summary, $vehicle_type_id)) {
                        $refreshed_summary = $flow->synchronizeSession(
                            (int)($summary['session']['lane_id'] ?? 0),
                            (string)($summary['session']['reg'] ?? ''),
                            isset($summary['session']['customer_number']) && $summary['session']['customer_number'] !== null
                                ? (int)$summary['session']['customer_number']
                                : null,
                            false,
                            $vehicle_type_id,
                            false,
                            [
                                'create_session' => false,
                                'subuser_id' => $subuser_id,
                            ]
                        );
                        if (!empty($refreshed_summary['session']['id'])) {
                            $summary = $refreshed_summary;
                        }
                    }

                    $response->success($summary);
                }

                self::requireParameters(['lane_id', 'reg']);
                $lane_id = (int)self::getParameter('lane_id');
                $reg = selfserve::standardize_registration((string)self::getParameter('reg'));

                $lane = $this->assertLaneAccess($user, $lane_id, $has_global, $has_own);
                $customer_number = null;
                if ($has_own && (!$has_global || !$this->userHasLaneDepartmentAccess($user, $lane))) {
                    $customer_number = $this->requireAuthenticatedCustomerNumber($user, 'list_department_selfserve_vehicle_conditions');
                }

                if ($vehicle_type_id !== null) {
                    $summary = $flow->synchronizeSession($lane_id, $reg, $customer_number, false, $vehicle_type_id, false, [
                        'create_session' => false,
                        'subuser_id' => $subuser_id,
                    ]);
                    if (empty($summary['session']['id'])) {
                        try {
                            $summary = $flow->getLatestSessionSummary($lane_id, $reg);
                        } catch (\RuntimeException) {
                            // Keep the read-only snapshot when no previous wash exists.
                        }
                    }
                } else {
                    $summary = $flow->getLatestSessionSummary($lane_id, $reg);
                }
                $this->assertSummaryAccess($user, $summary, $has_global, $has_own, 'list_department_selfserve_vehicle_conditions');
                $response->success($summary);
            } catch (\RuntimeException $e) {
                $response->error($e->getMessage(), 404);
            }
        }, [
            'list_department_selfserve_vehicle_conditions' => 'View self-serve wash summaries',
            'list_own_department_selfserve_vehicle_conditions' => 'View self-serve wash summaries for customer-scoped vehicles'
        ]);

        /**
         * Add a department self-serve vehicle condition
         */
        $this->post('/department/selfserve/vehicle/conditions', function () {
            global $response;
            [$user, $actor_id, $subuser_id] = $this->getAuthenticatedSelfServePrincipal();
            $own_permission = self::definePermission('add_own_department_selfserve_vehicle_conditions', subusers_permission_node_key::SELFSERVE_ADD);

            $customer_number_context = $this->resolveEffectiveCustomerNumber();
            $has_global = $user !== null && $this->hasPermission('add_department_selfserve_vehicle_conditions');
            $has_own = $this->hasPermission($own_permission, $customer_number_context);

            if (!$has_global && !$has_own) {
                $response->forbidden(['add_department_selfserve_vehicle_conditions', 'add_own_department_selfserve_vehicle_conditions']);
            }

            if ($user === null && !$has_own) {
                $response->error('Invalid session', 400);
            }

            $department = (int)$response->getRequestParameter('department');
            $lane = (int)$response->getRequestParameter('lane');
            $reg = selfserve::standardize_registration((string)$response->getRequestParameter('reg'));
            $question = (int)$response->getRequestParameter('question');
            $value = (bool)$response->getRequestParameter('value');

            if (!$department || !$lane || !$reg || !$question) {
                $response->error('Missing required fields', 400);
            }
            $vehicle_type_id = $this->resolveVehicleTypeIdFromRequest();
            $activate_machine = $this->requestBooleanFlag('activate_machine', true);
            $sync_relay_state = $this->requestBooleanFlag('sync_relay_state', true);

            if ($has_global) {
                $customer_id = $response->isRequestParameterSet('customer_id') ? (int)$response->getRequestParameter('customer_id') : null;
                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (!in_array($department, $authorized_department_ids, true)) {
                    $this->forbidDepartmentAccess($department);
                }
            } else {
                $customer_id = $this->requireAuthenticatedCustomerNumber($user, 'add_department_selfserve_vehicle_conditions');
            }

            try {
                $condition_o = new department_selfserve_vehicle_conditions_o();
                $condition_o->add($department, $lane, $reg, $question, $value, $customer_id);
                $summary = $this->getWashFlow()->synchronizeSession($lane, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state, [
                    'subuser_id' => $subuser_id,
                ]);
                (new logs_o())->add('department_selfserve_vehicle_conditions', 'global', 1, $actor_id, 'ADD_VEHICLE_CONDITION', 'User added department self-serve vehicle condition ' . $condition_o->id);
                $response->success([
                    'condition' => $condition_o->asArray(),
                    'selfserve' => $summary,
                ]);
            } catch (\Exception $e) {
                $response->error($e->getMessage(), 500);
            }
        }, [
            'add_department_selfserve_vehicle_conditions' => 'Add a department self-serve vehicle condition',
            'add_own_department_selfserve_vehicle_conditions' => 'Add customer-scoped department self-serve vehicle condition'
        ]);

        /**
         * Update a department self-serve vehicle condition
         */
        $this->put('/department/selfserve/vehicle/conditions', function () {
            global $response;
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $has_global = $user->hasPermission('update_department_selfserve_vehicle_conditions');
            $has_own = $user->hasPermission('update_own_department_selfserve_vehicle_conditions');

            if (!$has_global && !$has_own) {
                $response->forbidden(['update_department_selfserve_vehicle_conditions', 'update_own_department_selfserve_vehicle_conditions']);
            }

            $id = (int)$response->getRequestParameter('id');
            if (!$id) {
                $response->error('Missing required fields', 400);
            }

            $condition_o = new department_selfserve_vehicle_conditions_o();
            $condition_o->select($id);
            if (!$condition_o->exists()) {
                $response->error('Condition not found', 404);
            }

            $customer_number = (int)$user->customer_number->value();

            if ($has_global) {
                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (!in_array((int)$condition_o->department->value(), $authorized_department_ids, true)) {
                    $this->forbidDepartmentAccess((int)$condition_o->department->value());
                }
            } else {
                if ((int)$condition_o->customer_id->value() !== $customer_number) {
                    $response->forbidden(['update_department_selfserve_vehicle_conditions']);
                }
            }

            if ($response->isRequestParameterSet('department')) {
                $new_department = (int)$response->getRequestParameter('department');
                if ($has_global) {
                    $authorized_department_ids = $user->getGroup()->getDepartments();
                    if (!in_array($new_department, $authorized_department_ids, true)) {
                        $this->forbidDepartmentAccess($new_department);
                    }
                }
                $condition_o->department->update($new_department);
            }
            if ($response->isRequestParameterSet('lane')) {
                $condition_o->lane->update((int)$response->getRequestParameter('lane'));
            }
            if ($response->isRequestParameterSet('reg')) {
                $new_reg = selfserve::standardize_registration((string)$response->getRequestParameter('reg'));
                $condition_o->reg->update($new_reg);
            }
            if ($response->isRequestParameterSet('question')) {
                $condition_o->question->update((int)$response->getRequestParameter('question'));
            }
            if ($response->isRequestParameterSet('value')) {
                $condition_o->value->update((bool)$response->getRequestParameter('value'));
            }
            if ($response->isRequestParameterSet('customer_id')) {
                $new_customer_id = (int)$response->getRequestParameter('customer_id');
                if (!$has_global && $has_own && $new_customer_id !== $customer_number) {
                    $response->forbidden(['update_department_selfserve_vehicle_conditions']);
                }
                $condition_o->customer_id->update($new_customer_id);
            }
            $vehicle_type_id = $this->resolveVehicleTypeIdFromRequest();
            $activate_machine = $this->requestBooleanFlag('activate_machine', true);
            $sync_relay_state = $this->requestBooleanFlag('sync_relay_state', true);

            try {
                $summary = $this->getWashFlow()->synchronizeSession(
                    (int)$condition_o->lane->value(),
                    (string)$condition_o->reg->value(),
                    $condition_o->customer_id->value() === null ? null : (int)$condition_o->customer_id->value(),
                    $activate_machine,
                    $vehicle_type_id,
                    $sync_relay_state
                );
                (new logs_o())->add('department_selfserve_vehicle_conditions', 'global', 1, $user->id, 'UPDATE_VEHICLE_CONDITION', 'User updated department self-serve vehicle condition ' . $id);
                $response->success([
                    'condition' => $condition_o->asArray(),
                    'selfserve' => $summary,
                ]);
            } catch (\Exception $e) {
                $response->error($e->getMessage(), 500);
            }
        }, [
            'update_department_selfserve_vehicle_conditions' => 'Update a department self-serve vehicle condition',
            'update_own_department_selfserve_vehicle_conditions' => 'Update customer-scoped department self-serve vehicle condition'
        ]);

        /**
         * Delete a department self-serve vehicle condition
         */
        $this->delete('/department/selfserve/vehicle/conditions', function () {
            global $response;
            $user = (new authentication())->get_user();
            if (!$user) {
                $response->error('Invalid session', 400);
            }

            $has_global = $user->hasPermission('delete_department_selfserve_vehicle_conditions');
            $has_own = $user->hasPermission('delete_own_department_selfserve_vehicle_conditions');

            if (!$has_global && !$has_own) {
                $response->forbidden(['delete_department_selfserve_vehicle_conditions', 'delete_own_department_selfserve_vehicle_conditions']);
            }

            $id = (int)$response->getRequestParameter('id');
            if (!$id) {
                $response->error('Missing required fields', 400);
            }

            $condition_o = new department_selfserve_vehicle_conditions_o();
            $condition_o->select($id);
            if (!$condition_o->exists()) {
                $response->error('Condition not found', 404);
            }

            if ($has_global) {
                $authorized_department_ids = $user->getGroup()->getDepartments();
                if (!in_array((int)$condition_o->department->value(), $authorized_department_ids, true)) {
                    $this->forbidDepartmentAccess((int)$condition_o->department->value());
                }
            } else {
                if ((int)$condition_o->customer_id->value() !== (int)$user->customer_number->value()) {
                    $response->forbidden(['delete_department_selfserve_vehicle_conditions']);
                }
            }

            $lane_id = (int)$condition_o->lane->value();
            $reg = (string)$condition_o->reg->value();
            $customer_id = $condition_o->customer_id->value() === null ? null : (int)$condition_o->customer_id->value();
            $vehicle_type_id = $this->resolveVehicleTypeIdFromRequest();
            $activate_machine = $this->requestBooleanFlag('activate_machine', true);
            $sync_relay_state = $this->requestBooleanFlag('sync_relay_state', true);

            $condition_o->delete();

            try {
                $summary = $this->getWashFlow()->synchronizeSession($lane_id, $reg, $customer_id, $activate_machine, $vehicle_type_id, $sync_relay_state);
            } catch (\Throwable) {
                $summary = null;
            }

            (new logs_o())->add('department_selfserve_vehicle_conditions', 'global', 1, $user->id, 'DELETE_VEHICLE_CONDITION', 'User deleted department self-serve vehicle condition ' . $id);
            $response->success([
                'message' => 'Condition deleted',
                'selfserve' => $summary,
            ]);
        }, [
            'delete_department_selfserve_vehicle_conditions' => 'Delete a department self-serve vehicle condition',
            'delete_own_department_selfserve_vehicle_conditions' => 'Delete own department self-serve vehicle condition'
        ]);
    }

    private function getWashFlow(): selfserve_wash_flow
    {
        return new selfserve_wash_flow();
    }

    private function getAuthenticatedSelfServePrincipal(): array
    {
        global $response;

        $auth = new authentication();
        $user = $auth->get_user();
        if ($user !== false) {
            return [$user, (int)$user->id, null];
        }

        $subuser = $auth->get_subuser();
        if ($subuser !== false) {
            return [null, (int)$subuser->id, (int)$subuser->id];
        }

        $response->error('Invalid session', 400);
    }

    private function resolveVehicleTypeIdFromQuery(): ?int
    {
        $rawVehicleType = null;
        if (self::isParametersSet(['vehicle_type_id'])) {
            $rawVehicleType = self::getParameter('vehicle_type_id');
        } elseif (self::isParametersSet(['vehicle_type'])) {
            $rawVehicleType = self::getParameter('vehicle_type');
        }

        return $this->normalizeVehicleTypeOverride($rawVehicleType);
    }

    private function resolveVehicleTypeIdFromRequest(): ?int
    {
        global $response;

        $rawVehicleType = null;
        if ($response->isRequestParameterSet('vehicle_type_id')) {
            $rawVehicleType = $response->getRequestParameter('vehicle_type_id');
        } elseif ($response->isRequestParameterSet('vehicle_type')) {
            $rawVehicleType = $response->getRequestParameter('vehicle_type');
        } elseif (self::isParametersSet(['vehicle_type_id'])) {
            $rawVehicleType = self::getParameter('vehicle_type_id');
        } elseif (self::isParametersSet(['vehicle_type'])) {
            $rawVehicleType = self::getParameter('vehicle_type');
        }

        return $this->normalizeVehicleTypeOverride($rawVehicleType);
    }

    private function normalizeVehicleTypeOverride(mixed $rawVehicleType): ?int
    {
        global $response;

        if ($rawVehicleType === null) {
            return null;
        }

        try {
            return department_selfserve_tasks_o::normalizeVehicleTypeInput($rawVehicleType);
        } catch (\Exception $e) {
            $response->error('Invalid vehicle_type_id parameter: ' . $e->getMessage(), 400);
        }
    }

    private function shouldRefreshSummaryForVehicleType(array $summary, ?int $vehicleTypeIdOverride): bool
    {
        if ($vehicleTypeIdOverride === null) {
            return false;
        }

        $session = is_array($summary['session'] ?? null) ? $summary['session'] : [];
        if (($session['completed_at'] ?? null) !== null || selfserve_wash_sessions_o::isTerminalStatus($session['status'] ?? null)) {
            return false;
        }

        $sessionVehicleTypeId = isset($session['vehicle_type_id']) && $session['vehicle_type_id'] !== null
            ? (int)$session['vehicle_type_id']
            : null;
        if ($sessionVehicleTypeId !== $vehicleTypeIdOverride) {
            return true;
        }

        $questions = is_array($summary['questions'] ?? null) ? $summary['questions'] : [];
        $tasks = is_array($summary['tasks'] ?? null) ? $summary['tasks'] : [];
        return $questions === [] && $tasks === [];
    }

    private function requestBooleanFlag(string $parameter, bool $default): bool
    {
        if (!$this->isParametersSet([$parameter])) {
            return $default;
        }

        $value = $this->getParameter($parameter);
        if (is_bool($value)) {
            return $value;
        }
        if (is_int($value)) {
            return $value !== 0;
        }

        $normalized = strtolower(trim((string)$value));
        if (in_array($normalized, ['1', 'true', 'yes', 'on'], true)) {
            return true;
        }
        if (in_array($normalized, ['0', 'false', 'no', 'off'], true)) {
            return false;
        }

        return $default;
    }

    private function assertLaneAccess(
        ?object $user,
        int $laneId,
        bool $hasGlobalPermission = true,
        bool $hasOwnPermission = false,
        string $elevatedPermission = 'list_department_selfserve_vehicle_conditions'
    ): department_lanes_o
    {
        global $response;

        $lane = (new department_lanes_o())->select($laneId);
        if (!$lane->exists()) {
            $response->error('Department lane not found', 404);
        }

        if ($hasGlobalPermission && $user !== null && $this->userHasLaneDepartmentAccess($user, $lane)) {
            return $lane;
        }

        if ($hasOwnPermission && $this->isCustomerSelfServeLaneEnabled($lane)) {
            return $lane;
        }

        if ($hasGlobalPermission) {
            $lane_department_id = (int)$lane->department->value();
            $this->forbidDepartmentAccess($lane_department_id);
        }

        $response->forbidden([$elevatedPermission]);
    }

    private function userHasLaneDepartmentAccess(object $user, department_lanes_o $lane): bool
    {
        $lane_department_id = (int)$lane->department->value();
        $authorized_department_ids = array_values(array_filter(
            array_map('intval', (array)$user->getGroup()->getDepartments()),
            static fn(int $department_id): bool => $department_id > 0
        ));

        return in_array($lane_department_id, $authorized_department_ids, true);
    }

    private function isCustomerSelfServeLaneEnabled(department_lanes_o $lane): bool
    {
        try {
            if (!$lane->isSelfServeEnabled()) {
                return false;
            }

            $department = (new departments_o())->select((int)$lane->department->value());
            return $department->exists() && $department->getSelfServeEnabled();
        } catch (\Throwable) {
            return false;
        }
    }

    private function summaryBelongsToCustomer(?object $user, array $summary): bool
    {
        $customer_number = $this->requireAuthenticatedCustomerNumber($user, 'list_department_selfserve_vehicle_conditions');
        $session_customer_number = $summary['session']['customer_number'] ?? null;
        if ($session_customer_number !== null && (int)$session_customer_number === $customer_number) {
            return true;
        }

        $reg = (string)($summary['session']['reg'] ?? '');
        $vehicle_o = (new customer_vehicles_o())->selectByPlate($reg);
        return $vehicle_o->exists() && (int)$vehicle_o->customer_id->value() === $customer_number;
    }

    private function summaryDepartmentId(array $summary): int
    {
        return (int)($summary['lane']['department'] ?? $summary['session']['department_id'] ?? 0);
    }

    private function userHasSummaryDepartmentAccess(object $user, array $summary): bool
    {
        $lane_department = $this->summaryDepartmentId($summary);
        if ($lane_department <= 0) {
            return false;
        }

        $authorized_department_ids = array_values(array_filter(
            array_map('intval', (array)$user->getGroup()->getDepartments()),
            static fn(int $department_id): bool => $department_id > 0
        ));

        return in_array($lane_department, $authorized_department_ids, true);
    }

    private function requireAuthenticatedCustomerNumber(?object $user, string $elevatedPermission): int
    {
        global $response;

        $customer_number = $this->resolveEffectiveCustomerNumber();
        if ($customer_number === null && $user !== null && isset($user->customer_number)) {
            $customer_number = (int)$user->customer_number->value();
        }
        $customer_number = (int)$customer_number;
        if ($customer_number <= 0) {
            $response->forbidden([$elevatedPermission]);
        }

        return $customer_number;
    }

    private function assertSummaryAccess(
        ?object $user,
        array $summary,
        bool $hasGlobalPermission,
        bool $hasOwnPermission,
        string $elevatedPermission
    ): void
    {
        global $response;

        if ($hasGlobalPermission && $user !== null && $this->userHasSummaryDepartmentAccess($user, $summary)) {
            return;
        }

        if ($hasOwnPermission && $this->summaryBelongsToCustomer($user, $summary)) {
            return;
        }

        if ($hasGlobalPermission) {
            $this->forbidDepartmentAccess($this->summaryDepartmentId($summary));
        }

        $response->forbidden([$elevatedPermission]);
    }
}
