<?php

namespace Tests\Unit\Framework;

use Openguru\OpenCartFramework\Support\ExecutionTimeProfiler;
use PHPUnit\Framework\TestCase;

class ExecutionTimeProfilerTest extends TestCase
{
    public function testStartInitializesProfiler(): void
    {
        $profiler = new ExecutionTimeProfiler();
        $profiler->start();

        $result = $profiler->stop();

        $this->assertArrayHasKey('total_execution_time_ms', $result);
        $this->assertArrayHasKey('checkpoints', $result);
        $this->assertIsFloat($result['total_execution_time_ms']);
        $this->assertGreaterThanOrEqual(0, $result['total_execution_time_ms']);
    }

    public function testAddCheckpointRecordsCheckpoint(): void
    {
        $profiler = new ExecutionTimeProfiler();
        $profiler->start();
        
        usleep(10000); // 10ms
        $profiler->addCheckpoint('test_checkpoint');
        
        $result = $profiler->stop();

        $this->assertCount(2, $result['checkpoints']); // start + test_checkpoint + End
        $this->assertEquals('test_checkpoint', $result['checkpoints'][0]['label']);
        $this->assertArrayHasKey('elapsed_since_previous_ms', $result['checkpoints'][0]);
    }

    public function testStopReturnsCorrectStructure(): void
    {
        $profiler = new ExecutionTimeProfiler();
        $profiler->start();
        $profiler->addCheckpoint('checkpoint1');
        $profiler->addCheckpoint('checkpoint2');
        
        $result = $profiler->stop();

        $this->assertArrayHasKey('total_execution_time_ms', $result);
        $this->assertArrayHasKey('checkpoints', $result);
        $this->assertIsArray($result['checkpoints']);
        $this->assertCount(3, $result['checkpoints']); // checkpoint1, checkpoint2, End
    }

    public function testMultipleCheckpoints(): void
    {
        $profiler = new ExecutionTimeProfiler();
        $profiler->start();
        $profiler->addCheckpoint('first');
        usleep(5000);
        $profiler->addCheckpoint('second');
        usleep(5000);
        $profiler->addCheckpoint('third');
        
        $result = $profiler->stop();

        $this->assertCount(4, $result['checkpoints']);
        $this->assertEquals('first', $result['checkpoints'][0]['label']);
        $this->assertEquals('second', $result['checkpoints'][1]['label']);
        $this->assertEquals('third', $result['checkpoints'][2]['label']);
        $this->assertEquals('End', $result['checkpoints'][3]['label']);
    }

    public function testElapsedTimeIsCalculated(): void
    {
        $profiler = new ExecutionTimeProfiler();
        $profiler->start();
        
        usleep(10000); // 10ms
        $profiler->addCheckpoint('test');
        
        $result = $profiler->stop();

        $this->assertGreaterThan(0, $result['checkpoints'][0]['elapsed_since_previous_ms']);
        $this->assertIsFloat($result['checkpoints'][0]['elapsed_since_previous_ms']);
    }
}

