<?php

namespace Shm\ShmAuditLog;

use Exception;
use Shm\ShmAuth\Auth;
use Shm\ShmDB\mDB;
use Shm\ShmTypes\StructureType;
use Shm\ShmAuditLog\SchemaAuditLog\AuditLogs;

class ShmAuditLog
{

    public static function insert(StructureType $structure,  $idORIds, string | array $changes)
    {
        self::add($structure, $idORIds, $changes, 'insert');
    }

    public static function update(StructureType $structure,  $idORIds, string | array $changes)
    {
        self::add($structure, $idORIds, $changes, 'update');
    }

    public static function delete(StructureType $structure,  $changes, $idORIds)
    {
        self::add($structure, $idORIds, $changes, 'delete');
    }

    public static function action(StructureType $structure,  $idORIds, string | array $changes)
    {
        self::add($structure, $idORIds, $changes, 'action');
    }

    public static function error(StructureType $structure,  $idORIds, string | array $changes)
    {
        self::add($structure, $idORIds, $changes, 'error');
    }

    public static function system(StructureType $structure,  $idORIds, string | array $changes)
    {
        self::add($structure, $idORIds, $changes, 'system');
    }

    private static function add(StructureType $structure,  $idORIds, string | array | null $changes, $type)
    {

        $ids = [];


        if (is_array($idORIds)) {
            $ids = array_map(fn($id) => mDB::id($id), $idORIds);
        } else {
            $ids[] = mDB::id($idORIds);
        }



        if (is_string($changes)) {
            $changes = [$changes];
        }

        //Разбиваем $ids на чанки чтобы документ лога не был перегружен 
        $ids_chunks = array_chunk($ids, 10);

        $auditLogs = [];

        foreach ($changes as $key => $value) {

            foreach ($ids_chunks as $ids_chunk) {
                $auditLogs[] = [
                    'type' => $type,
                    'documents' => $ids_chunk,
                    'documentsCollection' => $structure->collection ?? null,
                    'owner' => Auth::getAuthID(),
                    'ownerCollection' => Auth::getAuthCollection(),
                    'changes' => $value,
                ];
            }
        }

        AuditLogs::structure()->insertMany($auditLogs);
    }
}