<?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
    {
        Schema::create('sales_import_batches', function (Blueprint $table) {
            $table->id();
            $table->date('import_date')->default(now());
            $table->decimal('total_quantity', 12, 4)->default(0);
            $table->decimal('total_amount', 12, 4)->default(0);
            $table->string('status')->default('pending')->comment('pending, confirmed, cancelled');
            $table->foreignId('imported_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('confirmed_at')->nullable();
            $table->text('note')->nullable();
            $table->timestamps();
        });

        Schema::create('sales_import_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('batch_id')->constrained('sales_import_batches')->cascadeOnDelete();
            $table->string('machine_id')->nullable()->comment('機台編號');
            $table->string('product_code')->comment('商品代碼');
            // product_id could be null if product not found at import time, but we should try to link it.
            // Constraint might fail if product doesn't exist, so maybe just foreignId without constrained first, 
            // or nullable constrained. Since we might import data for products not yet in system? 
            // Better to allow null product_id.
            $table->foreignId('product_id')->nullable()->constrained('products')->nullOnDelete();
            $table->timestamp('transaction_at')->nullable()->comment('交易時間');
            $table->string('transaction_serial')->nullable()->comment('交易序號');
            $table->decimal('quantity', 12, 4)->default(0);
            $table->decimal('amount', 12, 4)->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('sales_import_items');
        Schema::dropIfExists('sales_import_batches');
    }
};
