<?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('admin_pm_daily_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->onDelete('cascade')->comment('테넌트 ID');
            $table->foreignId('project_id')->nullable()->constrained('admin_pm_projects')->onDelete('set null')->comment('프로젝트 ID (선택)');
            $table->date('log_date')->comment('로그 날짜');
            $table->text('summary')->nullable()->comment('일일 요약');
            $table->foreignId('created_by')->constrained('users')->comment('작성자');
            $table->foreignId('updated_by')->nullable()->constrained('users')->comment('수정자');
            $table->foreignId('deleted_by')->nullable()->constrained('users')->comment('삭제자');
            $table->timestamps();
            $table->softDeletes();

            // 인덱스: 테넌트별 날짜 검색 최적화
            $table->index(['tenant_id', 'log_date']);
            // 유니크: 테넌트+날짜+프로젝트 조합 (프로젝트가 없는 경우 날짜당 하나)
            $table->unique(['tenant_id', 'log_date', 'project_id'], 'unique_tenant_date_project');
        });

        // 일일 로그 개별 항목 테이블
        Schema::create('admin_pm_daily_log_entries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('daily_log_id')->constrained('admin_pm_daily_logs')->onDelete('cascade')->comment('일일 로그 ID');
            $table->enum('assignee_type', ['team', 'user'])->default('user')->comment('담당자 유형');
            $table->unsignedBigInteger('assignee_id')->nullable()->comment('담당자 ID (팀 또는 사용자)');
            $table->string('assignee_name')->comment('담당자 이름 (직접 입력 또는 선택)');
            $table->text('content')->comment('업무 내용');
            $table->enum('status', ['todo', 'in_progress', 'done'])->default('todo')->comment('상태');
            $table->unsignedInteger('sort_order')->default(0)->comment('정렬 순서');
            $table->timestamps();

            // 인덱스: 로그별 정렬 순서
            $table->index(['daily_log_id', 'sort_order']);
            // 인덱스: 담당자별 검색
            $table->index(['assignee_type', 'assignee_id']);
        });
    }

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