<?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_quote_pipeline_daily', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id');
            $table->date('stat_date');

            // 견적
            $table->unsignedInteger('quote_created_count')->default(0);
            $table->decimal('quote_amount', 18, 2)->default(0);
            $table->unsignedInteger('quote_approved_count')->default(0);
            $table->unsignedInteger('quote_rejected_count')->default(0);
            $table->unsignedInteger('quote_conversion_count')->default(0)->comment('수주 전환 건수');
            $table->decimal('quote_conversion_rate', 5, 2)->default(0)->comment('전환율 (%)');

            // 영업 기회 (sales_prospects - tenant_id 없어 manager_id로 연결)
            $table->unsignedInteger('prospect_created_count')->default(0);
            $table->unsignedInteger('prospect_won_count')->default(0);
            $table->unsignedInteger('prospect_lost_count')->default(0);
            $table->decimal('prospect_amount', 18, 2)->default(0)->comment('파이프라인 금액');

            // 입찰
            $table->unsignedInteger('bidding_count')->default(0);
            $table->unsignedInteger('bidding_won_count')->default(0);
            $table->decimal('bidding_amount', 18, 2)->default(0);

            // 상담
            $table->unsignedInteger('consultation_count')->default(0);

            $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_quote_pipeline_daily');
    }
};