import { createRuleFactory } from "./createRuleFactory.js";

import type { CreateRuleFunction } from "./createRuleFactory.js";
import type { PureScopedStyleSheet } from "./createStylesheet.js";
import type { createVarFactory } from "./createVarFactory.js";

type CreateRuleParameters = Parameters<CreateRuleFunction>;
type CreateNestedQueryFunction = (query: string, rules: Record<string, CreateRuleParameters[0]>) => void;

const createNestedQueryFactory =
    (meta: PureScopedStyleSheet, varFactory: ReturnType<typeof createVarFactory>): CreateNestedQueryFunction =>
    (query, rules) => {
        const nestedRules: (typeof meta)["rules"] = new Map();
        const { rule: createRule } = createRuleFactory({ ...meta, rules: nestedRules }, varFactory);

        for (const selector in rules) {
            const properties = rules[selector];
            createRule({ forceSelector: selector, ...properties });
        }

        meta.rules.set(query, Object.fromEntries(nestedRules));
    };

export { type CreateNestedQueryFunction, createNestedQueryFactory };
