<?php

namespace Tests\Unit\AdOps;

use App\Services\AdOps\EventLogService;
use PHPUnit\Framework\TestCase;

/**
 * recursiveDiff replaces the legacy `array_diff_assoc($new, $old)` which cast
 * nested arrays to the literal string "Array" and silently dropped structural
 * changes from the audit log. These tests lock in the new behavior.
 */
final class EventLogServiceDiffTest extends TestCase
{
    public function testFlatDiffReportsOnlyChangedKeys(): void
    {
        $old  = ['name' => 'A', 'status' => 'active', 'bid' => 0.50];
        $new  = ['name' => 'A', 'status' => 'paused', 'bid' => 0.75];
        $diff = EventLogService::recursiveDiff($new, $old);

        $this->assertSame(['status' => 'paused', 'bid' => 0.75], $diff);
    }

    public function testNestedArrayChangeIsNotFlattenedToArrayString(): void
    {
        // Regression: array_diff_assoc cast nested arrays to 'Array' so
        // different nested arrays compared equal and the diff was empty.
        $old  = ['targeting' => ['states' => ['CA', 'TX']]];
        $new  = ['targeting' => ['states' => ['NY']]];
        $diff = EventLogService::recursiveDiff($new, $old);

        $this->assertSame(['targeting' => ['states' => ['NY']]], $diff);
    }

    public function testIdenticalNestedArraysProduceEmptyDiff(): void
    {
        $same = ['targeting' => ['states' => ['CA']]];
        $diff = EventLogService::recursiveDiff($same, $same);

        $this->assertSame([], $diff);
    }

    public function testKeyPresentInNewButAbsentInOldAppearsInDiff(): void
    {
        $old  = ['name' => 'A'];
        $new  = ['name' => 'A', 'budget' => 100];
        $diff = EventLogService::recursiveDiff($new, $old);

        $this->assertSame(['budget' => 100], $diff);
    }

    public function testScalarVsArrayValueIsReported(): void
    {
        $old  = ['targeting' => 'all'];
        $new  = ['targeting' => ['states' => ['CA']]];
        $diff = EventLogService::recursiveDiff($new, $old);

        $this->assertSame(['targeting' => ['states' => ['CA']]], $diff);
    }

    public function testPartialNestedChangeOnlyReportsChangedSubkeys(): void
    {
        $old  = ['targeting' => ['states' => ['CA'], 'cities' => ['LA']]];
        $new  = ['targeting' => ['states' => ['CA'], 'cities' => ['SF']]];
        $diff = EventLogService::recursiveDiff($new, $old);

        $this->assertSame(['targeting' => ['cities' => ['SF']]], $diff);
    }
}
