<?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_finance_monthly', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->smallInteger('stat_year');
            $table->tinyInteger('stat_month');

            $table->decimal('deposit_total', 18, 2)->default(0);
            $table->decimal('withdrawal_total', 18, 2)->default(0);
            $table->decimal('net_cashflow', 18, 2)->default(0);
            $table->decimal('purchase_total', 18, 2)->default(0);
            $table->decimal('card_total', 18, 2)->default(0);

            $table->decimal('receivable_end', 18, 2)->default(0)->comment('월말 미수금');
            $table->decimal('payable_end', 18, 2)->default(0)->comment('월말 미지급');
            $table->decimal('bank_balance_end', 18, 2)->default(0)->comment('월말 잔액');

            $table->decimal('mom_cashflow_change', 8, 2)->nullable()->comment('전월 대비 현금흐름 변화 (%)');

            $table->timestamps();

            $table->unique(['tenant_id', 'stat_year', 'stat_month'], 'uk_tenant_year_month');
            $table->index(['stat_year', 'stat_month']);
        });
    }

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