<?php

declare(strict_types=1);

namespace App\Shopware;

use App\Commerce\Dto\CommerceSearchQuery;

final class ShopwareCriteriaBuilder
{
    public function build(
        CommerceSearchQuery $query,
        ?int                $limit = 25,
        ?bool               $grouping = false
    ): array
    {
        $criteria = [
            'page' => 1,
            'limit' => max(1, $limit),
            'total-count-mode' => 0,
            'includes' => [
                'product' => [
                    'id',
                    'name',
                    'description',
                    'productNumber',
                    'available',
                    'calculatedPrice',
                    'seoUrls',
                    'manufacturer',
                    'translated.name',
                    'cover',
                    'customFields'
                ],
                'product_manufacturer' => [
                    'name',
                ],
                'calculated_price' => [
                    'unitPrice',
                    'totalPrice',
                    'referencePrice',
                    'listPrice',
                    'regulationPrice'
                ],
                'seo_url' => [
                    'seoPathInfo',
                ],
                'product_media' => [
                    'id',
                    'media'
                ],
                'media' => [
                    'id',
                    'url',
                    'thumbnails',
                    'alt',
                    'title'
                ]
            ],
            'associations' => [
                'manufacturer' => new \stdClass(),
                'seoUrls' => new \stdClass(),
                'cover' => [
                    'associations' => [
                        'media' => [
                            'associations' => [
                                "thumbnails" => new \stdClass()
                            ]
                        ]
                    ]
                ]
            ]
        ];

        if ($grouping) {
            $criteria["grouping"] = ["parentId"];
        }

        if ($query->searchText !== '') {
            $criteria['search'] = $query->searchText;
        }

        $filters = [
            [
                'type' => 'equals',
                'field' => 'active',
                'value' => true,
            ],
            [
                'type' => 'equals',
                'field' => 'available',
                'value' => true,
            ]
        ];

        if ($query->priceMin !== null) {
            $criteria['min-price'] = $query->priceMin;
        }

        if ($query->priceMax !== null) {
            $criteria['max-price'] = $query->priceMax;
        }

        $criteria['filter'] = $filters;

        return $criteria;
    }
}