<?php

namespace App\Console\Commands;

use App\Models\OrderNumber;
use App\Models\ProductGroup;
use Box\Spout\Common\Exception\IOException;
use Box\Spout\Common\Exception\UnsupportedTypeException;
use Box\Spout\Reader\Exception\ReaderNotOpenedException;
use Illuminate\Console\Command;

class EmegrendelesOrderNumberTest extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'emegrendeles:orderNumberTest {workerNumber=1}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Recovery and test order numbers from emegrendeles';

    protected $startOrderNumber = 4999;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private function getMaxSupplierOrderNumber(): int
    {
        // SELECT max(supplierOrderNumber) FROM `order_archives` WHERE deliveryDate>'2025-01-01';

        return \DB::table('order_archives')
            ->where('deliveryDate', '>', '2025-01-01')
            ->max('supplierOrderNumber');
    }

    private function setDefaultOrderNumberForSuppliers(): void
    {
        $this->info('Start setDefaultOrderNumberForSuppliers');
        $supplierIds = \DB::table('order_archives')
            ->selectRaw('DISTINCT(supplier_id)')
            ->orderBy('supplier_id')
            ->get();
        foreach ($supplierIds as $supplierId) {

            $o = OrderNumber::create([
                'id' => $this->startOrderNumber,
                'year' => 25,
                'supplier_id' => $supplierId->supplier_id,
                'order_id' => 1000 + $supplierId->supplier_id,
            ]);

        }
        $this->info('End setDefaultOrderNumberForSuppliers');
    }

    private function generateRandomSupplierNumber($count = 10000)
    {
        $this->info('Start generateRandomSupplierNumber');
        $supplierIds = \DB::table('order_archives')
            ->selectRaw('DISTINCT(supplier_id)')
            ->orderBy('supplier_id')
            ->get();
        $supplierIds = $supplierIds->pluck('supplier_id')->toArray();
        $startOrderID = $this->getMaxSupplierOrderNumber();
        $startOrderID += $this->argument('workerNumber') * $count;
        $this->info('Start generateRandomSupplierNumber from orderID:'.$startOrderID);
        for ($i = 0; $i < $count; $i++) {
            $randomSupplierId = $supplierIds[array_rand($supplierIds)];
            try {
                $o = OrderNumber::create([
                    'year' => 25,
                    'supplier_id' => $randomSupplierId,
                    'order_id' => $startOrderID + $i,
                ]);
                $this->info('Created OrderNumber: '.$o->id.' for supplier:'.$o->supplier_id);
            } catch (\Exception $e) {
                $this->error('Error creating Order  for supplier:'.$randomSupplierId.' - '.$e->getMessage());
            }
            usleep(rand(150, 600));
        }
        $this->info('End generateRandomSupplierNumber');
    }

    /**
     * Execute the console command.
     *
     *
     * @throws IOException
     * @throws UnsupportedTypeException
     * @throws ReaderNotOpenedException
     */
    public function handle(): int
    {
        var_dump(config('app.env', 'env'.now()));
        var_dump(config('app.stage', 'fuck'.now()));

        $DBMaxSupplierOrderNumber = $this->getMaxSupplierOrderNumber();
        if ($this->startOrderNumber < $DBMaxSupplierOrderNumber) {
            $this->error('Max startOrderNumber wrong. Set:'.
                $this->startOrderNumber.
                ' inDB:'.$DBMaxSupplierOrderNumber

            );

            return false;
        }

        \DB::table('order_numbers')->truncate();
        $this->setDefaultOrderNumberForSuppliers();

        // $this->generateRandomSupplierNumber();
        return 0;
        /*
                //$name = $this->argument('name');
                \Schema::disableForeignKeyConstraints();
                ProductGroup::truncate();
                \Schema::enableForeignKeyConstraints();
                $this->info('Import End');
                return 0;
         */
    }
}
