<?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('file_share_links', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('file_id')->comment('파일 ID');
            $table->unsignedBigInteger('tenant_id')->comment('테넌트 ID');

            // 공유 링크 정보
            $table->string('token', 64)->unique()->comment('공유 토큰 (64자 랜덤)');
            $table->timestamp('expires_at')->comment('만료 시간 (24시간 기본)');

            // 다운로드 추적
            $table->integer('download_count')->default(0)->comment('다운로드 횟수');
            $table->integer('max_downloads')->nullable()->comment('최대 다운로드 횟수 (null=무제한)');
            $table->timestamp('last_downloaded_at')->nullable()->comment('마지막 다운로드 시간');
            $table->string('last_downloaded_ip', 45)->nullable()->comment('마지막 다운로드 IP');

            // 감사 정보
            $table->unsignedBigInteger('created_by')->comment('생성자 ID');
            $table->timestamp('created_at')->useCurrent();

            // 인덱스
            $table->index(['file_id'], 'idx_file');
            $table->index(['tenant_id'], 'idx_tenant');
            $table->index(['token'], 'idx_token');
            $table->index(['expires_at'], 'idx_expires');

            // 외래키
            $table->foreign('file_id')->references('id')->on('files')->onDelete('cascade');
            $table->foreign('tenant_id')->references('id')->on('tenants')->onDelete('cascade');
        });
    }

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