<?php

app_require('classes/subuser_permission_templates_service.php');
app_require('modules/subusers/helpers/subusers_permission_node_key.php');

use classes\subuser_permission_templates_service;
use modules\subusers\helpers\subusers_permission_node_key;

it('exposes driver access templates with valid subuser permission node keys', function (): void {
    $service = new subuser_permission_templates_service();
    $templates = $service->templates();

    expect(array_column($templates, 'key'))
        ->toContain(subuser_permission_templates_service::TEMPLATE_DEACTIVATED)
        ->toContain(subuser_permission_templates_service::TEMPLATE_DRIVER)
        ->toContain(subuser_permission_templates_service::TEMPLATE_BOOKING_COORDINATOR)
        ->toContain(subuser_permission_templates_service::TEMPLATE_FLEET_ADMIN);

    foreach ($templates as $template) {
        foreach ($template['permissions'] as $permission) {
            expect(subusers_permission_node_key::tryFrom($permission))->not->toBeNull();
        }
    }
});

it('expands and classifies practical driver access templates', function (): void {
    $service = new subuser_permission_templates_service();

    $driver = $service->expandTemplate(subuser_permission_templates_service::TEMPLATE_DRIVER);
    $deactivated = $service->expandTemplate(subuser_permission_templates_service::TEMPLATE_DEACTIVATED);

    expect($driver['enabled'])->toBeTrue()
        ->and($driver['permissions'])
        ->toContain('VEHICLES_LIST')
        ->toContain('BOOKINGS_ADD')
        ->and($service->classify($driver['permissions'], true))
        ->toBe(subuser_permission_templates_service::TEMPLATE_DRIVER)
        ->and($deactivated['enabled'])
        ->toBeFalse()
        ->and($deactivated['permissions'])
        ->toBe([])
        ->and($service->classify(['VEHICLES_LIST'], false))
        ->toBe(subuser_permission_templates_service::TEMPLATE_DEACTIVATED)
        ->and($service->classify(['VEHICLES_LIST'], true))
        ->toBe(subuser_permission_templates_service::TEMPLATE_CUSTOM);
});

it('treats custom as a raw permissions marker in write payloads', function (): void {
    $service = new subuser_permission_templates_service();
    $driver = $service->expandTemplateForWritePayload(subuser_permission_templates_service::TEMPLATE_DRIVER);

    expect($service->expandTemplateForWritePayload(subuser_permission_templates_service::TEMPLATE_CUSTOM))
        ->toBeNull()
        ->and($driver['enabled'])
        ->toBeTrue()
        ->and($driver['permissions'])
        ->toBe([
            'VEHICLES_LIST',
            'SELFSERVE_LIST',
            'SELFSERVE_ADD',
            'BOOKINGS_LIST',
            'BOOKINGS_ADD',
            'ORDERS_LIST',
        ]);

    expect(fn () => $service->expandTemplateForWritePayload('missing-template'))
        ->toThrow(\InvalidArgumentException::class, 'Unknown driver access template.');
});
