<?php

namespace App\Support\ActivityLog;

use Spatie\Activitylog\Support\ActivityBuffer as SpatieActivityBuffer;
use Spatie\Activitylog\Support\Config;

class ActivityBuffer extends SpatieActivityBuffer
{
    public function flush(): void
    {
        if (empty($this->pending)) {
            return;
        }

        $records = $this->pending;

        // Collect all unique keys from all records
        $allKeys = [];
        foreach ($records as $record) {
            foreach ($record as $key => $val) {
                $allKeys[$key] = true;
            }
        }

        // Normalize records so that every record has the exact same keys in the same order
        $normalizedRecords = [];
        foreach ($records as $record) {
            $normalized = [];
            foreach ($allKeys as $key => $_) {
                $normalized[$key] = array_key_exists($key, $record) ? $record[$key] : null;
            }
            $normalizedRecords[] = $normalized;
        }

        $modelClass = Config::activityModel();

        $modelClass::query()->insert($normalizedRecords);

        $this->pending = [];
    }
}
