<?php

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

return new class extends Migration
{
    protected $connection = 'sam_stat';

    public function up(): void
    {
        Schema::connection($this->connection)->create('stat_inventory_daily', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->date('stat_date');

            // 재고 현황
            $table->unsignedInteger('total_sku_count')->default(0)->comment('총 SKU 수');
            $table->decimal('total_stock_qty', 18, 2)->default(0)->comment('총 재고 수량');
            $table->decimal('total_stock_value', 18, 2)->default(0)->comment('총 재고 금액');

            // 입출고
            $table->unsignedInteger('receipt_count')->default(0)->comment('입고 건수');
            $table->decimal('receipt_qty', 18, 2)->default(0);
            $table->decimal('receipt_amount', 18, 2)->default(0);
            $table->unsignedInteger('issue_count')->default(0)->comment('출고 건수');
            $table->decimal('issue_qty', 18, 2)->default(0);
            $table->decimal('issue_amount', 18, 2)->default(0);

            // 안전재고
            $table->unsignedInteger('below_safety_count')->default(0)->comment('안전재고 미달 품목 수');
            $table->unsignedInteger('zero_stock_count')->default(0)->comment('재고 0 품목 수');
            $table->unsignedInteger('excess_stock_count')->default(0)->comment('과잉 재고 품목 수');

            // 품질검사
            $table->unsignedInteger('inspection_count')->default(0);
            $table->unsignedInteger('inspection_pass_count')->default(0);
            $table->unsignedInteger('inspection_fail_count')->default(0);
            $table->decimal('inspection_pass_rate', 5, 2)->default(0)->comment('합격률 (%)');

            // 재고회전
            $table->decimal('turnover_rate', 8, 2)->default(0)->comment('재고회전율');

            $table->timestamps();

            $table->unique(['tenant_id', 'stat_date'], 'uk_tenant_date');
            $table->index('stat_date');
        });
    }

    public function down(): void
    {
        Schema::connection($this->connection)->dropIfExists('stat_inventory_daily');
    }
};