<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('contracts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');

            // 계약 기본 정보
            $table->string('contract_code', 50)->comment('계약번호');
            $table->string('project_name')->comment('현장명');

            // 거래처 정보
            $table->unsignedBigInteger('partner_id')->nullable()->comment('거래처 ID');
            $table->string('partner_name')->nullable()->comment('거래처명');

            // 담당자 정보
            $table->unsignedBigInteger('contract_manager_id')->nullable()->comment('계약담당자 ID');
            $table->string('contract_manager_name')->nullable()->comment('계약담당자명');
            $table->unsignedBigInteger('construction_pm_id')->nullable()->comment('공사PM ID');
            $table->string('construction_pm_name')->nullable()->comment('공사PM명');

            // 계약 상세
            $table->integer('total_locations')->default(0)->comment('총 개소');
            $table->decimal('contract_amount', 15, 2)->default(0)->comment('계약금액');
            $table->date('contract_start_date')->nullable()->comment('계약시작일');
            $table->date('contract_end_date')->nullable()->comment('계약종료일');

            // 상태 정보
            $table->string('status', 20)->default('pending')->comment('계약상태: pending, completed');
            $table->string('stage', 30)->default('estimate_selected')->comment('계약단계: estimate_selected, estimate_progress, delivery, installation, inspection, other');

            // 연결 정보
            $table->unsignedBigInteger('bidding_id')->nullable()->comment('입찰 ID');
            $table->string('bidding_code', 50)->nullable()->comment('입찰번호');

            // 비고
            $table->text('remarks')->nullable()->comment('비고');

            // 활성화 상태
            $table->boolean('is_active')->default(true)->comment('활성화 여부');

            // 감사 컬럼
            $table->unsignedBigInteger('created_by')->nullable()->comment('생성자 ID');
            $table->unsignedBigInteger('updated_by')->nullable()->comment('수정자 ID');
            $table->unsignedBigInteger('deleted_by')->nullable()->comment('삭제자 ID');

            // 타임스탬프
            $table->timestamps();
            $table->softDeletes();

            // 인덱스
            $table->index('tenant_id');
            $table->index('partner_id');
            $table->index('status');
            $table->index('stage');
            $table->unique(['tenant_id', 'contract_code']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('contracts');
    }
};
