<?php

use classes\economic_v2_distribution_service;
use classes\economic_v2_versioning_service;

if (!function_exists('economic_v2_integration_db')) {
    function economic_v2_integration_db(): \classes\db
    {
        if (!integration_enabled()) {
            test()->markTestSkipped('Set RUN_INTEGRATION_TESTS=1 to run DB integration tests.');
        }

        $host = getenv('CONFIG_DB_HOST') ?: null;
        $user = getenv('CONFIG_DB_USER') ?: null;
        $password = getenv('CONFIG_DB_PASSWORD') ?: '';
        $database = getenv('CONFIG_DB_DATABASE') ?: null;
        $port = (int)(getenv('CONFIG_DB_PORT') ?: 3306);
        if (!$host || !$user || !$database) {
            test()->markTestSkipped('Missing DB env vars: CONFIG_DB_HOST/CONFIG_DB_USER/CONFIG_DB_DATABASE.');
        }

        app_require('classes/db.php');
        app_require('classes/orders_schema_bootstrap.php');
        app_require('classes/economic_v2_schema_bootstrap.php');
        app_require('classes/economic_v2_versioning_service.php');
        app_require('classes/economic_v2_distribution_service.php');

        if (!defined('redis')) {
            define('redis', new class {
                public function get(string $key)
                {
                    return null;
                }

                public function set(string $key, $value, int $ttl = 0): bool
                {
                    return true;
                }

                public function delete(string $key): bool
                {
                    return true;
                }

                public function clear_keys(string $pattern): int
                {
                    return 0;
                }

                public function __call(string $name, array $arguments)
                {
                    return null;
                }
            });
        }

        global $ECONOMIC_API;
        $ECONOMIC_API = [
            'app_access_grant' => (string)(getenv('ECONOMIC_API_APP_ACCESS_GRANT') ?: ''),
            'app_access_grant2' => (string)(getenv('ECONOMIC_API_APP_ACCESS_GRANT2') ?: ''),
            'app_secret_token' => (string)(getenv('ECONOMIC_API_APP_SECRET_TOKEN') ?: ''),
        ];

        $GLOBALS['response'] = new class {
            public function internal_server_error(string $message): void
            {
                throw new RuntimeException($message);
            }
        };

        $db = new \classes\db([
            'host' => $host,
            'user' => $user,
            'password' => $password,
            'database' => $database,
            'port' => $port,
        ]);
        $db->connect();
        $GLOBALS['db'] = $db;
        return $db;
    }
}

if (!function_exists('economic_v2_distribution_credentials_available')) {
    function economic_v2_distribution_credentials_available(): bool
    {
        $accessGrant = trim((string)(getenv('ECONOMIC_API_APP_ACCESS_GRANT') ?: ''));
        $secretToken = trim((string)(getenv('ECONOMIC_API_APP_SECRET_TOKEN') ?: ''));

        return $accessGrant !== '' && $secretToken !== '';
    }
}

it('runs best-effort backfill repeatedly without introducing duplicate same-start rows', function (): void {
    if (getenv('RUN_BACKFILL_INTEGRATION_TESTS') !== '1') {
        test()->markTestSkipped('Set RUN_BACKFILL_INTEGRATION_TESTS=1 to run backfill integration test.');
    }

    $db = economic_v2_integration_db();
    try {
        $service = new economic_v2_versioning_service();
        $first = $service->runBestEffortBackfill();
        $second = $service->runBestEffortBackfill();

        expect($first)->toHaveKey('fixed_pricing');
        expect($first)->toHaveKey('vehicle_subscriptions');
        expect($first)->toHaveKey('discount_overrides');
        expect($second)->toHaveKey('fixed_pricing');

        $dupFixed = $db->fetch_assoc($db->query(
            "SELECT COUNT(*) AS c
             FROM (
               SELECT customer_number, effective_from, COUNT(*) AS cc
               FROM customer_fixed_pricing_versions
               WHERE source LIKE 'backfill.%'
               GROUP BY customer_number, effective_from
               HAVING cc > 1
             ) t"
        ));
        $dupVehicle = $db->fetch_assoc($db->query(
            "SELECT COUNT(*) AS c
             FROM (
               SELECT customer_number, reg, effective_from, COUNT(*) AS cc
               FROM customer_vehicle_subscription_versions
               WHERE source LIKE 'backfill.%'
               GROUP BY customer_number, reg, effective_from
               HAVING cc > 1
             ) t"
        ));
        $dupDiscount = $db->fetch_assoc($db->query(
            "SELECT COUNT(*) AS c
             FROM (
               SELECT user_id, customer_number, is_category, object_id, effective_from, COUNT(*) AS cc
               FROM customer_discount_override_versions
               WHERE source LIKE 'backfill.%'
               GROUP BY user_id, customer_number, is_category, object_id, effective_from
               HAVING cc > 1
             ) t"
        ));

        expect((int)($dupFixed['c'] ?? 0))->toBe(0);
        expect((int)($dupVehicle['c'] ?? 0))->toBe(0);
        expect((int)($dupDiscount['c'] ?? 0))->toBe(0);
    } finally {
        $db->close();
    }
});

it('resolves version-aware distribution payload shapes over a real date range', function (): void {
    if (getenv('RUN_ECONOMIC_V2_DISTRIBUTION_INTEGRATION_TESTS') !== '1') {
        test()->markTestSkipped('Set RUN_ECONOMIC_V2_DISTRIBUTION_INTEGRATION_TESTS=1 to run e-conomic distribution integration test.');
    }

    if (!economic_v2_distribution_credentials_available()) {
        test()->markTestSkipped('Missing ECONOMIC_API_APP_ACCESS_GRANT / ECONOMIC_API_APP_SECRET_TOKEN for live e-conomic distribution integration run.');
    }

    $db = economic_v2_integration_db();
    try {
        $service = new economic_v2_distribution_service();
        $dateFrom = date('Y-m-01');
        $dateTo = date('Y-m-d');

        $fixed = $service->getFixedPricingDistribution($dateFrom, $dateTo);
        $subscriptions = $service->getWashSubscriptionsDistribution($dateFrom, $dateTo);
        $prices = $service->getCustomerPricesDistribution($dateFrom, $dateTo);

        expect($fixed)->toHaveKey('customers');
        expect($fixed)->toHaveKey('collective_results');
        expect($subscriptions)->toHaveKey('customers');
        expect($subscriptions)->toHaveKey('collective_results');
        expect($prices)->toHaveKey('customers');
        expect($prices)->toHaveKey('collective_results');
    } finally {
        $db->close();
    }
});
