<?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('barobill_billing_records', function (Blueprint $table) {
            $table->id();
            $table->foreignId('member_id')->comment('바로빌 회원사 ID');
            $table->string('billing_month', 7)->comment('과금 월 (YYYY-MM)');
            $table->enum('service_type', ['tax_invoice', 'bank_account', 'card', 'hometax'])
                  ->comment('서비스 유형');
            $table->enum('billing_type', ['subscription', 'usage'])
                  ->comment('과금 유형: subscription=월정액, usage=건별');
            $table->unsignedInteger('quantity')->default(1)->comment('수량 (월정액=1, 건별=사용건수)');
            $table->unsignedInteger('unit_price')->default(0)->comment('단가 (원)');
            $table->unsignedInteger('total_amount')->default(0)->comment('총액 (원)');
            $table->date('billed_at')->comment('과금일');
            $table->text('description')->nullable()->comment('설명');
            $table->timestamps();

            // 인덱스
            $table->index(['member_id', 'billing_month']);
            $table->index(['billing_month', 'service_type']);
            $table->index(['billing_month', 'billing_type']);
            $table->index('billed_at');

            // 중복 방지 (같은 월, 같은 서비스, 같은 과금유형)
            $table->unique(['member_id', 'billing_month', 'service_type', 'billing_type'], 'billing_unique');

            // 외래키
            $table->foreign('member_id')
                  ->references('id')
                  ->on('barobill_members')
                  ->onDelete('cascade');
        });
    }

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