<?php

app_require('classes/workfeed_employee_name_formatter.php');

use classes\workfeed_employee_name_formatter;

function workfeed_employee_name_from_record(mixed $record): ?string
{
    return workfeed_employee_name_formatter::fromRecord($record, [
        'firstname',
        'firstName',
        'first_name',
        'employee.firstname',
        'employee.firstName',
        'employee.first_name',
    ], [
        'lastname',
        'lastName',
        'last_name',
        'employee.lastname',
        'employee.lastName',
        'employee.last_name',
    ], [
        'employeeName',
        'employee.name',
        'name',
        'displayName',
    ]);
}

it('formats workfeed employee display names from the documented firstname lastname schema', function (): void {
    $name = workfeed_employee_name_from_record((object)[
        'id' => 'employee_1',
        'firstname' => 'API 2',
        'lastname' => 'Test 2',
    ]);

    expect($name)->toBe('API 2 Test 2');
});

it('prefers workfeed schema names over generic display name fields', function (): void {
    $name = workfeed_employee_name_from_record((object)[
        'employee' => (object)[
            'id' => 'employee_2',
            'firstname' => 'Jane',
            'lastname' => 'Doe',
            'name' => 'Wrong Name',
        ],
        'employeeName' => 'Also Wrong',
    ]);

    expect($name)->toBe('Jane Doe');
});

it('falls back to legacy display name fields when schema names are absent', function (): void {
    $name = workfeed_employee_name_from_record((object)[
        'employeeID' => 'employee_3',
        'employeeName' => 'Legacy Name',
    ]);

    expect($name)->toBe('Legacy Name');
});

it('ignores placeholder workfeed display names', function (): void {
    $name = workfeed_employee_name_from_record((object)[
        'employeeID' => 'employee_4',
        'employeeName' => 'Unknown employee',
    ]);

    expect($name)->toBeNull();
});

it('ignores employee id placeholder display names when the id is known', function (): void {
    $name = workfeed_employee_name_formatter::fromRecord((object)[
        'employeeID' => 'employee_5',
        'employeeName' => 'Employee employee_5',
    ], [
        'firstname',
    ], [
        'lastname',
    ], [
        'employeeName',
    ], 'employee_5');

    expect($name)->toBeNull();
});
