<?php

namespace KupShop\StoresBundle\Inspection;

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

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

        $batches = $this->getWrongBatches();

        $messages = [];
        foreach ($batches as $batch) {
            $messages[] = sprintf(translate('productWrongBatch', 'batches_inspections', false, true),
                $batch['code'],
                $batch['store_name'],
                $batch['batch_code']
            );
        }

        if ($messages) {
            $errors[] = new SimpleMessage(
                sprintf(translate('productsWrongBatches', 'batches_inspections', false, true),
                    count($batches)
                ), $messages);
        }

        return $errors;
    }

    private function getWrongBatches()
    {
        $productsBatches = sqlQueryBuilder()->select('si.*')->from('stores_items', 'si')
            ->addSelect(BatchesQuery::joinStoreBatches())
            ->andWhere('pb.id IS NOT NULl');

        return sqlQueryBuilder()->select('s.name store_name, COALESCE(pv.code, p.code) code, si.id_product, id_variation, batch_code,quantity, SUM(batch_quantity) batches_sum')->from('('.$productsBatches->getSQL().')',
            'si')
            ->leftJoin('si', 'stores', 's', 'si.id_store = s.id')
            ->innerJoin('si', 'products', 'p', 'p.id = si.id_product')
            ->leftJoin('si', 'products_variations', 'pv', 'si.id_variation = pv.id ')
            ->groupBy('id_store, id_product, id_variation')
            ->having('quantity < batches_sum')
            ->execute()->fetchAllAssociative();
    }

    public function isEnabled(): bool
    {
        return findModule(\Modules::PRODUCTS_BATCHES);
    }
}
