<?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::create('stock_counts', function (Blueprint $table) {
            $table->id();
            $table->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained('academies');
            $table->foreignId('warehouse_id')->constrained('warehouses');
            $table->string('count_number', 50);
            $table->string('status', 20)->default('open');
            $table->timestamp('started_at');
            $table->timestamp('completed_at')->nullable();
            $table->text('notes')->nullable();
            $table->integer('total_items')->default(0);
            $table->integer('total_discrepancies')->default(0);
            $table->bigInteger('total_variance_value')->default(0);
            $table->foreignId('created_by')->constrained('users');
            $table->foreignId('completed_by')->nullable()->constrained('users');
            $table->jsonb('metadata')->default('{}');
            $table->timestamps();
            $table->softDeletes();

            $table->index(['academy_id', 'status']);
            $table->index('warehouse_id');
        });

        DB::statement("ALTER TABLE stock_counts ADD CONSTRAINT stock_counts_status_check CHECK (status IN ('open', 'in_progress', 'completed', 'cancelled'))");

        Schema::create('stock_count_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('stock_count_id')->constrained('stock_counts')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products');
            $table->integer('system_quantity');
            $table->integer('counted_quantity')->nullable();
            $table->integer('discrepancy')->nullable();
            $table->bigInteger('discrepancy_value')->nullable();
            $table->string('status', 20)->default('pending');
            $table->foreignId('counted_by')->nullable()->constrained('users');
            $table->timestamp('counted_at')->nullable();
            $table->text('notes')->nullable();
            $table->timestamps();

            $table->index('stock_count_id');
            $table->index(['product_id', 'stock_count_id']);
        });

        DB::statement("ALTER TABLE stock_count_items ADD CONSTRAINT stock_count_items_status_check CHECK (status IN ('pending', 'counted', 'verified', 'adjusted'))");
    }

    public function down(): void
    {
        Schema::dropIfExists('stock_count_items');
        Schema::dropIfExists('stock_counts');
    }
};
