/**
 * SchemaService
 * Assembles atlas categories, traits, options, and user-contributed images into
 * the hierarchical schema structure consumed by the frontend form editor.
 */
class SchemaService {
    constructor(traitRepository) {
        this.traitRepository = traitRepository;
    }

    async getFullFormSchema(atlasId) {
        if (!atlasId) throw new Error("Atlas ID is required");
        const categories = await this.traitRepository.getAllCategories(atlasId);

        return await Promise.all(categories.map(async (cat) => {
            const traits = await this.traitRepository.getTraitsByCategory(cat.id);

            const znaky = await Promise.all(traits.map(async (trait) => {
                const options = await this.traitRepository.getOptionsByTrait(trait.id);

                const enrichedOptions = await Promise.all(options.map(async (opt) => {
                    const allUserImages = await this.traitRepository.getUserImagesByOption(opt.id);

                    return {
                        ...opt,
                        factoryImages: opt.images || [],
                        factoryDrawings: opt.drawings || [],
                        userImages: allUserImages
                            .filter(img => !img.is_drawing)
                            .map(img => ({ id: img.id, path: img.image_path })),

                        userDrawings: allUserImages
                            .filter(img => img.is_drawing)
                            .map(img => ({ id: img.id, path: img.image_path }))
                    };
                }));

                return { ...trait, options: enrichedOptions };
            }));

            return { ...cat, znaky };
        }));
    }
}

module.exports = SchemaService;