<?php

use classes\customer_mass_import_service;

if (!function_exists('fakeCustomerMassImportUser')) {
    function fakeCustomerMassImportUser(int $id, bool $hasPassword, string $displayName = 'Demo Company'): object
    {
        return new class($id, $hasPassword, $displayName) {
            public int $id;
            public bool $has_password;
            public string $display_name;

            public function __construct(int $id, bool $hasPassword, string $displayName)
            {
                $this->id = $id;
                $this->has_password = $hasPassword;
                $this->display_name = $displayName;
            }

            public function exists(): bool
            {
                return true;
            }

            public function hasPassword(): bool
            {
                return $this->has_password;
            }
        };
    }
}

if (!class_exists('CustomerMassImportServiceProbe')) {
    class CustomerMassImportServiceProbe extends customer_mass_import_service
    {
        public array $economicSearchResults = [];
        public array $createCalls = [];
        public array $bootstrapCalls = [];
        public array $syncCalls = [];
        public array $logEntries = [];
        public bool $localExists = false;
        public ?object $localUser = null;
        public ?object $bootstrapUser = null;
        public ?object $createResponse = null;
        public string $companyName = 'Probe Company';

        protected function searchEconomicCustomersByCvr(string $cvr): array
        {
            return $this->economicSearchResults;
        }

        protected function createEconomicCustomer(array $normalized): object
        {
            $this->createCalls[] = $normalized;
            return $this->createResponse ?? (object)[
                'customerNumber' => (int)$normalized['customer_number'],
            ];
        }

        protected function localCustomerNumberExists(int $customerNumber): bool
        {
            return $this->localExists;
        }

        protected function loadLocalCustomerByNumber(int $customerNumber): ?object
        {
            return $this->localUser;
        }

        protected function bootstrapLocalCustomerOrFail(int $customerNumber): object
        {
            $this->bootstrapCalls[] = $customerNumber;

            if ($this->bootstrapUser === null) {
                throw new RuntimeException('Customer was created in e-conomic but could not be imported locally.', 500);
            }

            return $this->bootstrapUser;
        }

        protected function fetchCompanyNameByCvr(string $cvr): string
        {
            return $this->companyName;
        }

        protected function logIssue(string $action, array $context): void
        {
            $this->logEntries[] = [
                'action' => $action,
                'context' => $context,
            ];
        }

        protected function syncLocalCustomer(object $customer, array $normalized, array &$warnings): void
        {
            $this->syncCalls[] = [
                'customer' => $customer,
                'normalized' => $normalized,
            ];
        }
    }
}

it('imports a matching e-conomic customer into the local system when no local record exists', function (): void {
    $service = new CustomerMassImportServiceProbe();
    $service->economicSearchResults = [
        (object)[
            'customerNumber' => 76964600,
            'name' => 'SPF-DANMARK A/S',
        ],
    ];
    $service->bootstrapUser = fakeCustomerMassImportUser(41, false, 'SPF-DANMARK A/S');

    $result = $service->import([
        'cvr' => '31744520',
        'name' => 'SPF-DANMARK A/S',
        'email' => 'spf@example.com',
        'ean' => '5790000000001',
        'phone' => '76964600',
    ]);

    expect($service->createCalls)->toBe([]);
    expect($service->bootstrapCalls)->toBe([76964600]);
    expect($result['action'])->toBe('imported_existing_customer');
    expect($result['existing_economic_customer'])->toBeTrue();
    expect($result['created_economic_customer'])->toBeFalse();
    expect($result['has_account'])->toBeFalse();
    expect($result['user_id'])->toBe(41);
});

it('reports when the local customer already has a login account', function (): void {
    $service = new CustomerMassImportServiceProbe();
    $service->localExists = true;
    $service->localUser = fakeCustomerMassImportUser(77, true, 'STEA A/S');
    $service->economicSearchResults = [
        (object)[
            'customerNumber' => 75773355,
            'name' => 'STEA A/S',
        ],
    ];

    $result = $service->import([
        'cvr' => '26761751',
        'name' => 'STEA A/S',
        'phone' => '75773355',
    ]);

    expect($service->bootstrapCalls)->toBe([]);
    expect($result['action'])->toBe('account_already_exists');
    expect($result['existing_local_customer'])->toBeTrue();
    expect($result['has_account'])->toBeTrue();
});

it('creates a new e-conomic customer and returns a created result for new rows', function (): void {
    $service = new CustomerMassImportServiceProbe();
    $service->bootstrapUser = fakeCustomerMassImportUser(105, false, 'TGP TRANSPORT APS');
    $service->createResponse = (object)[
        'customerNumber' => 22725567,
    ];

    $result = $service->import([
        'cvr' => '29424764',
        'name' => 'TGP TRANSPORT APS',
        'email' => 'tgp@example.com',
        'ean' => '5790001234567',
        'phone' => '22725567',
    ]);

    expect($service->createCalls)->toHaveCount(1);
    expect($service->createCalls[0]['customer_number'])->toBe(22725567);
    expect($service->createCalls[0]['ean'])->toBe('5790001234567');
    expect($service->bootstrapCalls)->toBe([22725567]);
    expect($result['action'])->toBe('created_customer');
    expect($result['created_economic_customer'])->toBeTrue();
    expect($result['existing_economic_customer'])->toBeFalse();
    expect($result['has_account'])->toBeFalse();
});

it('rejects EAN values longer than e-conomic accepts before creating customers', function (): void {
    $service = new CustomerMassImportServiceProbe();

    $call = static fn() => $service->import([
        'cvr' => '29424764',
        'name' => 'TGP TRANSPORT APS',
        'email' => 'tgp@example.com',
        'ean' => '57900012345678',
        'phone' => '22725567',
    ]);

    expect($call)->toThrow(RuntimeException::class, 'EAN must be at most 13 digits.');
    expect($service->createCalls)->toBe([]);
    expect($service->bootstrapCalls)->toBe([]);
});

it('creates the economic record for an existing local account when no matching upstream customer exists', function (): void {
    $service = new CustomerMassImportServiceProbe();
    $service->localExists = true;
    $service->localUser = fakeCustomerMassImportUser(222, true, 'Existing Account');
    $service->createResponse = (object)[
        'customerNumber' => 97120896,
    ];

    $result = $service->import([
        'cvr' => '49422113',
        'name' => 'VESTERBRO PRODUKTHANDEL',
        'phone' => '97120896',
    ]);

    expect($service->createCalls)->toHaveCount(1);
    expect($service->bootstrapCalls)->toBe([]);
    expect($result['action'])->toBe('economic_customer_created_for_existing_account');
    expect($result['existing_local_customer'])->toBeTrue();
    expect($result['created_economic_customer'])->toBeTrue();
    expect($result['has_account'])->toBeTrue();
});

it('rejects CVR conflicts when the upstream customer number does not match the submitted phone number', function (): void {
    $service = new CustomerMassImportServiceProbe();
    $service->economicSearchResults = [
        (object)[
            'customerNumber' => 87654321,
            'name' => 'Conflict Company',
        ],
    ];

    $call = static fn() => $service->import([
        'cvr' => '33333333',
        'name' => 'Conflict Company',
        'phone' => '22725567',
    ]);

    expect($call)->toThrow(RuntimeException::class, 'CVR already registered under customer number 87654321.');
    expect($service->createCalls)->toBe([]);
    expect($service->logEntries[0]['action'] ?? null)->toBe('CUSTOMER_MASS_IMPORT_CONFLICT');
});

it('registers the customer import route and wires it through the mass import service', function (): void {
    $routeFile = app_path('routes/customerSearchRoute.php');
    $content = file_get_contents($routeFile);

    expect($content)->not->toBeFalse();
    expect($content)->toContain("\$this->post('/customers/import'");
    expect($content)->toContain('new customer_mass_import_service()');
    expect($content)->toContain("\$this->requirePermission('add_user');");
});
