<?php

use App\Enums\StokOpnameStatus;
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('stok_opnames', function (Blueprint $table): void {
            $table->id();

            $table->foreignId('created_by_id')->constrained('users')->cascadeOnDelete();
            $table->foreignId('verified_by_id')->nullable()->constrained('users')->nullOnDelete();

            $table->date('opname_date');
            $table->enum('status', StokOpnameStatus::values())->default(StokOpnameStatus::DRAFT->value);
            $table->text('notes')->nullable();
            $table->text('verification_notes')->nullable();

            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();
            $table->softDeletes();
        });

        Schema::create('stok_opname_items', function (Blueprint $table): void {
            $table->id();

            $table->foreignId('stok_opname_id')->constrained('stok_opnames')->cascadeOnDelete();
            $table->foreignId('product_variant_id')->constrained('product_variants')->cascadeOnDelete();

            $table->unsignedInteger('system_stock')->default(0);
            $table->unsignedInteger('physical_stock')->default(0);
            $table->integer('difference')->default(0);
            $table->text('notes')->nullable();

            $table->timestamp('created_at')->useCurrent();
            $table->timestamp('updated_at')->useCurrent()->useCurrentOnUpdate();

            $table->unique(['stok_opname_id', 'product_variant_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('stok_opname_items');
        Schema::dropIfExists('stok_opnames');
    }
};
