import { profileCardLayoutFromMetadata } from "@/features/resources/profileCardLayout.js";
import { mp4AlphaLayoutFromMetadata, mp4AlphaLayoutKey } from "@/features/resources/mp4AlphaLayout.js";

export const emptyResourceMetadata = "{}";

export function resourceMetadataJSON(resourceType, metadataJson) {
    const metadata = {};
    const profileCardLayout = resourceType === "profile_card" ? profileCardLayoutFromMetadata(metadataJson) : null;
    if (profileCardLayout) {
        metadata.profile_card_layout = profileCardLayout;
    }
    const mp4AlphaLayout = mp4AlphaLayoutFromMetadata(metadataJson);
    if (mp4AlphaLayout) {
        metadata.animation_format = "mp4";
        metadata[mp4AlphaLayoutKey] = mp4AlphaLayout;
    }
    return Object.keys(metadata).length ? JSON.stringify(metadata) : emptyResourceMetadata;
}

export function removeProfileCardLayoutMetadata(metadataJson) {
    const metadata = parseMetadataObject(metadataJson);
    delete metadata.profile_card_layout;
    return stringifyMetadata(metadata);
}

export function metadataWithProfileCardLayout(metadataJson, layout) {
    const metadata = parseMetadataObject(metadataJson);
    if (layout) {
        metadata.profile_card_layout = layout;
    } else {
        delete metadata.profile_card_layout;
    }
    return stringifyMetadata(metadata);
}

function parseMetadataObject(metadataJson) {
    const normalized = String(metadataJson || "").trim();
    if (!normalized) {
        return {};
    }
    try {
        const parsed = JSON.parse(normalized);
        return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
    } catch {
        return {};
    }
}

function stringifyMetadata(metadata) {
    const clean = {};
    Object.entries(metadata || {}).forEach(([key, value]) => {
        if (value !== undefined && value !== null && value !== "") {
            clean[key] = value;
        }
    });
    return Object.keys(clean).length ? JSON.stringify(clean) : emptyResourceMetadata;
}
