<?php
// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

namespace Shopware\Plugins\ViisonCommon\Classes\Installation\AttributeColumn;

use InvalidArgumentException;
use Shopware\Components\Model\ModelManager;
use Shopware\Plugins\ViisonCommon\Classes\Installation\SQLHelper;

class AttributeColumnUninstaller
{
    /**
     * @var ModelManager
     */
    private $entityManager;

    /**
     * @var SQLHelper
     */
    private $sqlHelper;

    /**
     * @param ModelManager $entityManager
     * @param SQLHelper $sqlHelper
     */
    public function __construct(ModelManager $entityManager, SQLHelper $sqlHelper)
    {
        $this->entityManager = $entityManager;
        $this->sqlHelper = $sqlHelper;
    }

    /**
     * @param AttributeColumnDescription[]
     * @throws InvalidArgumentException if one of the passed elements is not of type AttributeColumnDescription.
     */
    public function removeAttributeColumnsIfExist(array $attributeColumnDescriptions)
    {
        $updatedTables = [];
        foreach ($attributeColumnDescriptions as $columnDescription) {
            // Validate the column description
            if (!($columnDescription instanceof AttributeColumnDescription)) {
                throw new InvalidArgumentException('The passed column description must be of type AttributeColumnDescription.');
            }

            // Drop the column
            $this->sqlHelper->dropColumnIfExists(
                $columnDescription->getTableName(),
                $columnDescription->getColumnName()
            );
            $updatedTables[] = $columnDescription->getTableName();
        }

        $this->entityManager->generateAttributeModels($updatedTables);
    }
}
