<?php

namespace Myvetshop\Module\Clinique\Command\Migrate;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

class RemoveRecommendedPrice extends Command
{
    private \Db $db;

    public function __construct(\Db $db)
    {
        parent::__construct('app:migrate:remove-recommended-price');

        $this->db = $db;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $styledOutput = new SymfonyStyle($input, $output);

        $styledOutput->writeln('Removing group reduction');
        if (!$this->db->execute('TRUNCATE TABLE ' . _DB_PREFIX_ . 'group_reduction')) {
            $styledOutput->error('Error while truncating group_reduction table');

            return 1;
        }

        $styledOutput->writeln('Removing forced prices specific_price table');
        if (!$this->db->execute('DELETE FROM ' . _DB_PREFIX_ . 'specific_price WHERE from_quantity = 1')) {
            $styledOutput->error('Error while purging specific_price table');

            return 1;
        }

        $styledOutput->writeln('Migrating per_group specific_price to all groups');
        if (!$this->db->execute('UPDATE ' . _DB_PREFIX_ . 'specific_price SET id_group = 0 WHERE id_group=4')) {
            $styledOutput->error('Error while migrating per_group specific_price');

            return 1;
        }
        if (!$this->db->execute('DELETE FROM ' . _DB_PREFIX_ . 'specific_price  WHERE from_quantity = 2 AND id_group > 0')) {
            $styledOutput->error('Error purging specific_price');

            return 1;
        }

        $styledOutput->writeln('Nulling tarif_privilege in ps_myvetshop_tarif_specifique table');
        if (!$this->db->execute('UPDATE ' . _DB_PREFIX_ . 'myvetshop_tarif_specifique SET tarif_privilege = NULL')) {
            $styledOutput->error('Error while updating myvetshop_tarif_specifique table');

            return 1;
        }

        if (!$this->db->execute('DELETE FROM ' . _DB_PREFIX_ . 'myvetshop_tarif_specifique WHERE tarif_privilege IS NULL AND tarif_fardelage IS NULL')) {
            $styledOutput->error('Error while purging myvetshop_tarif_specifique table');

            return 1;
        }

        $styledOutput->writeln('Puring ps_product_group_reduction_cache');
        if (!$this->db->execute('DELETE FROM ' . _DB_PREFIX_ . 'product_group_reduction_cache')) {
            $styledOutput->error('Error while purging product_group_reduction_cache table');

            return 1;
        }

        return 0;
    }
}
