
import {diffTranslations, getDiffLabel} from "./diffTranslations";

export type DiffChange = {
    key: string;
    label: string;
    oldValue: any;
    newValue: any;
    type: "created" | "updated" | "deleted" | "unchanged";
    typeLabel: "erstellt" | "geändert" | "gelöscht" | "unverändert";
};

const IGNORED_KEYS = new Set([
    "updated_at",
    "updated_by",
    "created_at",
    "created_by",
    "id",
    "phases"
]);

/**
 * Vergleicht zwei Objekte und gibt die Änderungen zurück.
 * @param obj1 Altes Objekt
 * @param obj2 Neues Objekt
 * @param ctx Lookup-Objekte (z. B. { projects, customers, vendors, profiles, plants })
 */
export function diffObjects(
    obj1: Record<string, any>,
    obj2: Record<string, any>,
    ctx: Record<string, any> = {}
): DiffChange[] {
    const diffs: DiffChange[] = [];

    const allKeys = new Set([
        ...Object.keys(obj1 || {}),
        ...Object.keys(obj2 || {}),
    ]);

    for (const key of allKeys) {
        if (IGNORED_KEYS.has(key)) continue; // Felder überspringen

        const oldVal = obj1?.[key];
        const newVal = obj2?.[key];

        // Wenn beides null/undefined → ignorieren
        if (
            (oldVal === null || oldVal === undefined || oldVal === "" || JSON.stringify(oldVal) === "[]") &&
            (newVal === null || newVal === undefined || newVal === "" || JSON.stringify(newVal) === "[]")
        ) {
            continue;
        }

        let type: DiffChange["type"] = "unchanged";
        let typeLabel: DiffChange["typeLabel"] = "unverändert";
        if (oldVal === newVal) {
            type = "unchanged";
            typeLabel = "unverändert";
        } else if (oldVal === undefined) {
            type = "created";
            typeLabel = "erstellt"
        } else if (newVal === undefined) {
            type = "deleted";
            typeLabel = "gelöscht"
        } else {
            type = "updated";
            typeLabel = "geändert"
        }

        if (type === "unchanged") continue;

        const translation = diffTranslations[key];
        let label = getDiffLabel(key);
        let resolvedOld = oldVal;
        let resolvedNew = newVal;

        if (translation) {
            if (translation.resolve) {
                const { oldVal: resOld, newVal: resNew } = translation.resolve(
                    oldVal,
                    newVal,
                    ctx
                );
                resolvedOld = resOld;
                resolvedNew = resNew;
            }
        }

        diffs.push({
            key,
            label,
            typeLabel,
            oldValue: resolvedOld ?? "-",
            newValue: resolvedNew ?? "-",
            type,
        });
    }

    return diffs;
}
