<?php

namespace KupShop\WarehouseBundle\Inspection;

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

class EANDuplicateInspection extends Inspection implements UserInspectionInterface
{
    private function fetchDuplicateEANs(): array
    {
        $products = sqlQueryBuilder()->select('p.ean')
            ->from('products', 'p')
            ->where('p.ean IS NOT NULL')
            ->groupBy('p.ean')
            ->having('COUNT(p.id) > 1')
            ->execute()->fetchFirstColumn();

        $productsVariations = sqlQueryBuilder()->select('p.ean')
            ->from('products_variations', 'p')
            ->where('p.ean IS NOT NULL')
            ->groupBy('p.ean')
            ->having('COUNT(p.id) > 1')
            ->execute()->fetchFirstColumn();

        $across = sqlQueryBuilder()
            ->select('p.ean')->distinct()
            ->from('products', 'p')
            ->join('p', 'products_variations', 'pv', 'p.ean = pv.ean')
            ->where('pv.ean IS NOT NULL')
            ->andWhere('p.ean IS NOT NULL')
            ->execute()->fetchFirstColumn();

        return array_merge($products, $productsVariations, $across);
    }

    public function runInspection(): ?array
    {
        $errors = [];

        $duplicates = $this->fetchDuplicateEANs();
        if (count($duplicates) > 0) {
            $errors[] = new SimpleMessage(
                sprintf(
                    translate('duplicateProductEAN', 'warehouse_inspections', false, true),
                    implode(', ', $duplicates)
                )
            );
        }

        return $errors;
    }
}
