<?php

use classes\db;
use classes\economic_v2_versioning_service;

function economic_v2_versioning_integration_db(): 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/economic_v2_schema_bootstrap.php');
    app_require('classes/economic_v2_versioning_service.php');

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

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

it('creates closes and rotates fixed pricing versions without overlap', function (): void {
    $db = economic_v2_versioning_integration_db();
    $service = new economic_v2_versioning_service();
    $customer = 99000000 + random_int(1000, 9999);

    try {
        $db->query("DELETE FROM customer_fixed_pricing_versions WHERE customer_number = $customer");

        $first = $service->recordFixedPricingVersion($customer, 1000, 'Initial', '2026-01-01 00:00:00');
        $second = $service->recordFixedPricingVersion($customer, 1200, 'Updated', '2026-02-01 00:00:00');

        expect($first['action'])->toBe('inserted');
        expect($second['action'])->toBe('inserted');

        $rows = $db->fetch_all($db->query(
            "SELECT id, effective_from, effective_to, price
             FROM customer_fixed_pricing_versions
             WHERE customer_number = $customer
             ORDER BY effective_from ASC, id ASC"
        ));
        expect(count($rows))->toBe(2);
        expect((string)$rows[0]['effective_to'])->toBe('2026-01-31 23:59:59');
        expect((int)$rows[1]['price'])->toBe(1200);

        $service->closeActiveFixedPricingVersion($customer, '2026-02-15 00:00:00');
        $row = $db->fetch_assoc($db->query(
            "SELECT effective_to
             FROM customer_fixed_pricing_versions
             WHERE customer_number = $customer
             ORDER BY effective_from DESC
             LIMIT 1"
        ));
        expect((string)$row['effective_to'])->toBe('2026-02-15 00:00:00');
    } finally {
        $db->query("DELETE FROM customer_fixed_pricing_versions WHERE customer_number = $customer");
        $db->close();
    }
});

it('tracks vehicle and discount version lifecycles with closure semantics', function (): void {
    $db = economic_v2_versioning_integration_db();
    $service = new economic_v2_versioning_service();
    $customer = 99100000 + random_int(1000, 9999);
    $userId = 700000 + random_int(1000, 9999);
    $reg = 'ZZ' . random_int(1000, 9999);

    try {
        $db->query("DELETE FROM customer_vehicle_subscription_versions WHERE customer_number = $customer AND reg = '" . $db->escape_string($reg) . "'");
        $db->query("DELETE FROM customer_discount_override_versions WHERE customer_number = $customer AND user_id = $userId");

        $service->recordVehicleSubscriptionVersion([
            'vehicle_id' => null,
            'customer_number' => $customer,
            'reg' => $reg,
            'vehicle_type' => 1,
            'wash_subscription' => true,
        ], '2026-01-01 00:00:00');
        $service->recordVehicleSubscriptionVersion([
            'vehicle_id' => null,
            'customer_number' => $customer,
            'reg' => $reg,
            'vehicle_type' => 33,
            'wash_subscription' => true,
        ], '2026-01-10 00:00:00');
        $service->closeActiveVehicleSubscriptionVersion($customer, $reg, '2026-01-20 00:00:00');

        $vehicleRows = $db->fetch_all($db->query(
            "SELECT vehicle_type, effective_from, effective_to
             FROM customer_vehicle_subscription_versions
             WHERE customer_number = $customer
               AND reg = '" . $db->escape_string($reg) . "'
             ORDER BY effective_from ASC"
        ));
        expect(count($vehicleRows))->toBe(2);
        expect((string)$vehicleRows[0]['effective_to'])->toBe('2026-01-09 23:59:59');
        expect((string)$vehicleRows[1]['effective_to'])->toBe('2026-01-20 00:00:00');

        $service->recordDiscountOverrideVersion(
            $userId,
            $customer,
            false,
            33,
            25,
            '2026-01-01 00:00:00'
        );
        $service->recordDiscountOverrideVersion(
            $userId,
            $customer,
            false,
            33,
            0,
            '2026-01-15 00:00:00'
        );

        $discountRows = $db->fetch_all($db->query(
            "SELECT discount, effective_from, effective_to
             FROM customer_discount_override_versions
             WHERE customer_number = $customer
               AND user_id = $userId
               AND is_category = 0
               AND object_id = '33'
             ORDER BY effective_from ASC"
        ));
        expect(count($discountRows))->toBe(1);
        expect((int)$discountRows[0]['discount'])->toBe(25);
        expect((string)$discountRows[0]['effective_to'])->toBe('2026-01-15 00:00:00');
    } finally {
        $db->query("DELETE FROM customer_vehicle_subscription_versions WHERE customer_number = $customer");
        $db->query("DELETE FROM customer_discount_override_versions WHERE customer_number = $customer AND user_id = $userId");
        $db->close();
    }
});
