<?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('bills', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');
            $table->string('bill_number', 50)->comment('어음번호');
            $table->enum('bill_type', ['received', 'issued'])->comment('어음 구분: received=수취, issued=발행');
            $table->unsignedBigInteger('client_id')->nullable()->comment('거래처 ID');
            $table->string('client_name', 100)->nullable()->comment('비회원 거래처명');
            $table->decimal('amount', 15, 2)->comment('금액');
            $table->date('issue_date')->comment('발행일');
            $table->date('maturity_date')->comment('만기일');
            $table->string('status', 30)->default('stored')->comment('상태: stored/maturityAlert/maturityResult/paymentComplete/dishonored/collectionRequest/collectionComplete/suing');
            $table->string('reason', 255)->nullable()->comment('사유');
            $table->unsignedInteger('installment_count')->default(0)->comment('차수');
            $table->text('note')->nullable()->comment('메모/비고');
            $table->boolean('is_electronic')->default(false)->comment('전자어음 여부');
            $table->unsignedBigInteger('bank_account_id')->nullable()->comment('입금/출금 계좌 ID');
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자 ID');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자 ID');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자 ID');
            $table->softDeletes();
            $table->timestamps();

            $table->index(['tenant_id', 'bill_type', 'status'], 'idx_tenant_type_status');
            $table->index(['tenant_id', 'maturity_date'], 'idx_tenant_maturity');
            $table->index('client_id', 'idx_client');
            $table->unique(['tenant_id', 'bill_number'], 'uk_tenant_bill_number');
        });

        // 어음 차수 관리 테이블 (installments)
        Schema::create('bill_installments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('bill_id')->comment('어음 ID');
            $table->date('installment_date')->comment('차수 일자');
            $table->decimal('amount', 15, 2)->comment('차수 금액');
            $table->text('note')->nullable()->comment('비고');
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자 ID');
            $table->timestamps();

            $table->foreign('bill_id')->references('id')->on('bills')->onDelete('cascade');
            $table->index('bill_id', 'idx_bill');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('bill_installments');
        Schema::dropIfExists('bills');
    }
};
