<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('held_sales', function (Blueprint $table) {
            $table->id();
            // No DB-level FK on tenant_id (integrity comes from BelongsToTenant +
            // TenantScope), matching every other owned table in this app.
            $table->unsignedBigInteger('tenant_id')->nullable()->index();
            $table->string('reference', 20); // H-000042, unique per tenant
            $table->foreignId('branch_id')->constrained('warehouses')->cascadeOnUpdate()->restrictOnDelete();
            $table->foreignId('till_id')->nullable()->constrained('tills')->cascadeOnUpdate()->nullOnDelete();
            $table->foreignId('pos_session_id')->nullable()->constrained('pos_sessions')->cascadeOnUpdate()->nullOnDelete();
            $table->foreignId('customer_id')->nullable()->constrained('customers')->cascadeOnUpdate()->nullOnDelete();
            $table->enum('discount_type', ['fixed', 'percentage'])->nullable();
            $table->decimal('discount_value', 12, 2)->default(0);
            $table->string('note', 500)->nullable();
            $table->timestamp('held_at');
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();
            $table->unique(['tenant_id', 'reference']);
            $table->index(['branch_id', 'held_at']);
        });

        Schema::create('held_sale_items', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->nullable()->index();
            $table->foreignId('held_sale_id')->constrained('held_sales')->cascadeOnDelete();
            $table->foreignId('product_id')->nullable()->constrained('products')->nullOnDelete();
            $table->foreignId('product_bundle_id')->nullable()->constrained('product_bundles')->nullOnDelete();
            $table->string('product_name', 255);
            $table->decimal('quantity', 12, 4);
            $table->decimal('unit_price', 12, 2);
            $table->decimal('vat_rate', 5, 2)->default(0);
            $table->enum('discount_type', ['fixed', 'percentage'])->nullable();
            $table->decimal('discount_value', 12, 2)->default(0);
            $table->foreignId('stock_batch_id')->nullable()->constrained('stock_batches')->nullOnDelete();
            $table->json('selected_serial_ids')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('held_sale_items');
        Schema::dropIfExists('held_sales');
    }
};
