<?php

namespace App\Http\Middleware;

use App\Services\Database\SchemaUpdater;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckSchemaMiddleware
{
    protected $schemaUpdater;

    public function __construct(SchemaUpdater $schemaUpdater)
    {
        $this->schemaUpdater = $schemaUpdater;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        /************** version 1.8 *************/
        // add tabs column to products tabl (added in v1.8)
        $this->schemaUpdater->addColumnToTable('products', 'tabs', 'text', [
            'nullable' => true,
        ], 'warnings');
        // add guide column to products table
        $this->schemaUpdater->addColumnToTable('products', 'guide', 'text', [
            'nullable' => true,
        ], 'warnings');
        // add send_time column to inventories table
        $this->schemaUpdater->addColumnToTable('inventories', 'send_time', 'string', [
            'nullable' => true,
        ], 'image');

        /************* version 2.1 *************/
        // add model_3d column to products table
        $this->schemaUpdater->addColumnToTable('products', 'model_3d', 'text', [
            'nullable' => true,
        ], 'videos');
        // add purchase_price column to inventories table
        $this->schemaUpdater->addColumnToTable('inventories', 'purchase_price', 'unsignedBigInteger', [
            'nullable' => true,
        ], 'weight');
        // add original column to inventories table
        $this->schemaUpdater->addColumnToTable('inventories', 'original', 'boolean', [
            'default' => true,
        ], 'max_sale');
        // add used column to inventories table
        $this->schemaUpdater->addColumnToTable('inventories', 'used', 'boolean', [
            'default' => false,
        ], 'max_sale');
        // add return_response column to transactions table
        $this->schemaUpdater->addColumnToTable('transactions', 'return_response', 'text', [
            'nullable' => true,
        ], 'gateway_reference_id');
        // add payment_transaction_uuid column to order_groups table
        $this->schemaUpdater->addColumnToTable('order_groups', 'payment_transaction_uuid', 'text', [
            'nullable' => true,
        ], 'uuid');

        /************* version 2.6 *************/
        // add description column to inventories table
        $this->schemaUpdater->addColumnToTable('inventories', 'description', 'text', [
            'nullable' => true,
        ], 'image');

        return $next($request);
    }
}
