import { ShopCatalogFilterService } from "../services/ShopCatalogFilterService.js";

export class ShopRestockProfileModel {
    static normalize(data = {}) {
        const seen = new Set();
        const entries = [];
        for (const source of Array.isArray(data.entries) ? data.entries : []) {
            const providerId = String(source.providerId || "");
            const productId = String(source.productId || "");
            const key = `${providerId}::${productId}`;
            if (!providerId || !productId || seen.has(key)) continue;
            seen.add(key);
            const quantityMin = Math.max(0, Math.floor(Number(source.quantity?.min) || 0));
            const quantityMax = Math.max(quantityMin, Math.floor(Number(source.quantity?.max) || 0));
            entries.push({
                providerId,
                productId,
                enabled: source.enabled !== false,
                weight: Math.max(1, Math.floor(Number(source.weight) || 1)),
                quantity: { min: quantityMin, max: quantityMax },
                priceOverride: source.priceOverride !== null && source.priceOverride !== undefined && Number.isFinite(Number(source.priceOverride))
                    ? Math.max(0, Math.round(Number(source.priceOverride))) : null,
                labelHint: String(source.labelHint || ""),
                sourceHint: String(source.sourceHint || "")
            });
        }
        const countMin = Math.max(1, Math.floor(Number(data.generation?.countMin) || 8));
        const quantityMin = Math.max(1, Math.floor(Number(data.generation?.quantityMin) || 1));
        return {
            schemaVersion: 1,
            entries,
            discovery: ShopCatalogFilterService.normalizeState(data.discovery || {}),
            generation: {
                countMin,
                countMax: Math.max(countMin, Math.floor(Number(data.generation?.countMax) || 14)),
                quantityMin,
                quantityMax: Math.max(quantityMin, Math.floor(Number(data.generation?.quantityMax) || 3)),
                preserveCurated: data.generation?.preserveCurated !== false
            },
            preset: {
                id: String(data.preset?.id || ""),
                moduleId: String(data.preset?.moduleId || ""),
                size: ["modest", "standard", "extensive"].includes(data.preset?.size) ? data.preset.size : "standard",
                sourceMode: data.preset?.sourceMode === "all" ? "all" : "recommended",
                includeSpecial: data.preset?.includeSpecial === true,
                customized: data.preset?.customized === true,
                maximumLevel: Number.isFinite(Number(data.preset?.maximumLevel))
                    ? Math.max(0, Math.floor(Number(data.preset.maximumLevel))) : null
            },
            revision: Math.max(0, Math.floor(Number(data.revision) || 0))
        };
    }
}
