<?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('purchases', function (Blueprint $table) {
            $table->ulid('id')->primary();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('store_id')->nullable();
            $table->string('local_id')->nullable();
            $table->string('supplier_id')->nullable();
            $table->string('supplier_name')->nullable();
            $table->string('invoice_number')->nullable();
            $table->string('payment_method')->nullable();
            $table->decimal('subtotal', 14, 4)->default(0);
            $table->decimal('discount_amount', 14, 4)->default(0);
            $table->decimal('tax_amount', 14, 4)->default(0);
            $table->decimal('total_amount', 14, 4)->default(0);
            $table->decimal('amount_paid', 14, 4)->default(0);
            $table->string('status')->default('received'); // received, partial, pending
            $table->text('notes')->nullable();
            $table->timestamp('purchase_date')->nullable();
            // Sync
            $table->string('device_id')->nullable();
            $table->bigInteger('sync_version')->default(0);
            $table->boolean('is_deleted')->default(false);
            $table->softDeletes();
            $table->timestamps();

            $table->index('user_id');
            $table->index(['user_id', 'store_id']);
            $table->index(['user_id', 'purchase_date']);
            $table->index(['user_id', 'updated_at']);
        });

        Schema::create('purchase_items', function (Blueprint $table) {
            $table->ulid('id')->primary();
            $table->string('purchase_id');
            $table->string('product_id')->nullable();
            $table->string('local_product_id')->nullable();
            $table->string('product_name');
            $table->string('product_barcode')->nullable();
            $table->decimal('unit_cost', 14, 4)->default(0);
            $table->decimal('quantity', 14, 4)->default(1);
            $table->decimal('tax_percent', 8, 4)->default(0);
            $table->decimal('subtotal', 14, 4)->default(0);
            $table->timestamps();

            $table->index('purchase_id');
            $table->index('product_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('purchase_items');
        Schema::dropIfExists('purchases');
    }
};
