<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Add tax_id to sales order lines
        Schema::table('core_sales_order_lines', function (Blueprint $table) {
            if (! Schema::hasColumn('core_sales_order_lines', 'tax_id')) {
                $table->foreignId('tax_id')
                    ->nullable()
                    ->after('product_variant_id')
                    ->constrained('core_tax_configurations')
                    ->nullOnDelete();
            }

            // Add tax_rate column to snapshot the rate at time of order
            if (! Schema::hasColumn('core_sales_order_lines', 'tax_rate')) {
                $table->decimal('tax_rate', 5, 2)->nullable()->after('tax_id');
            }
        });

        // Add tax_id to purchase order lines
        Schema::table('core_purchase_order_lines', function (Blueprint $table) {
            if (! Schema::hasColumn('core_purchase_order_lines', 'tax_id')) {
                $table->foreignId('tax_id')
                    ->nullable()
                    ->after('product_variant_id')
                    ->constrained('core_tax_configurations')
                    ->nullOnDelete();
            }

            // Add tax_rate column to snapshot the rate at time of order
            if (! Schema::hasColumn('core_purchase_order_lines', 'tax_rate')) {
                $table->decimal('tax_rate', 5, 2)->nullable()->after('tax_id');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('core_sales_order_lines', function (Blueprint $table) {
            if (Schema::hasColumn('core_sales_order_lines', 'tax_id')) {
                $table->dropForeign(['tax_id']);
                $table->dropColumn(['tax_id', 'tax_rate']);
            }
        });

        Schema::table('core_purchase_order_lines', function (Blueprint $table) {
            if (Schema::hasColumn('core_purchase_order_lines', 'tax_id')) {
                $table->dropForeign(['tax_id']);
                $table->dropColumn(['tax_id', 'tax_rate']);
            }
        });
    }
};
