<?php

namespace KupShop\WarehouseBundle\Inspection;

use KupShop\SystemInspectionBundle\Inspections\Inspection;
use KupShop\SystemInspectionBundle\Inspections\User\UserInspectionInterface;
use KupShop\SystemInspectionBundle\InspectionWriters\MessageTypes\SimpleMessage;

class NonVariantProductsInspection extends Inspection implements UserInspectionInterface
{
    public function runInspection(): ?array
    {
        $errors = [];

        $missingVariations = $this->getMissingVariations();

        foreach ($missingVariations as &$mv) {
            $mv = sprintf(
                translate('productWithoutVariation', 'warehouse_inspections', false, true),
                $mv['id_product'],
                $mv['code'],
                $mv['position_code'],
                $mv['pieces'],
                $mv['title']
            );
        }

        if ($missingVariations) {
            $errors[] = new SimpleMessage(
                sprintf(
                    translate('productsWithoutVariations', 'warehouse_inspections', false, true),
                    count($missingVariations)
                ),
                $missingVariations
            );
        }

        return $errors;
    }

    private function getMissingVariations()
    {
        return sqlQueryBuilder()
            ->select('wp.id_product, p.code, wpos.code position_code, wp.pieces, p.title')
            ->from('warehouse_products', 'wp')
            ->innerJoin('wp', 'products_variations', 'pv', 'pv.id_product = wp.id_product')
            ->innerJoin('wp', 'warehouse_positions', 'wpos', 'wp.id_position = wpos.id')
            ->innerJoin('pv', 'products', 'p', 'pv.id_product = p.id')
            ->where('wp.id_variation IS NULL AND wp.pieces > 0')
            ->groupBy('pv.id_product')->execute()->fetchAllAssociative();
    }
}
