<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('purchase_order_items', function (Blueprint $table) {
            $table->decimal('quantity_received_posted', 18, 4)->default(0)->after('quantity_ordered');
        });

        Schema::table('goods_receipts', function (Blueprint $table) {
            $table->foreignId('warehouse_id')->nullable()->after('purchase_order_id')
                ->constrained('inventory_warehouses')->restrictOnDelete();
            $table->uuid('correlation_id')->nullable()->after('status');
            $table->foreignId('actor_user_id')->nullable()->after('correlation_id')->constrained('users')->nullOnDelete();
            $table->timestamp('posted_at')->nullable()->after('actor_user_id');
        });

        DB::table('purchase_orders')->where('status', 'open')->update(['status' => 'draft']);
        DB::table('goods_receipts')->where('status', 'pending')->update(['status' => 'draft']);

        Schema::create('procurement_receipt_post_idempotency_keys', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('idempotency_key', 191);
            $table->string('idempotency_source', 64)->default('default');
            $table->foreignId('goods_receipt_id')
                ->constrained('goods_receipts', 'id', 'prc_gr_post_gr_fk')
                ->cascadeOnDelete();
            $table->json('result_payload');
            $table->timestamp('created_at')->useCurrent();

            $table->unique(['tenant_id', 'idempotency_key', 'idempotency_source'], 'prc_gr_post_idem_uq');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('procurement_receipt_post_idempotency_keys');

        Schema::table('goods_receipts', function (Blueprint $table) {
            $table->dropForeign(['warehouse_id']);
            $table->dropForeign(['actor_user_id']);
            $table->dropColumn(['warehouse_id', 'correlation_id', 'actor_user_id', 'posted_at']);
        });

        Schema::table('purchase_order_items', function (Blueprint $table) {
            $table->dropColumn('quantity_received_posted');
        });

    }
};
