<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('meeting_types', function (Blueprint $table) {
            $table->id();
            $table->string('key')->unique();
            $table->string('name');
            $table->string('default_title')->nullable();
            $table->unsignedSmallInteger('suggested_duration')->nullable();
            $table->text('agenda_template')->nullable();
            $table->text('minutes_template')->nullable();
            $table->json('participant_roles')->nullable();
            $table->json('recurrence_rule')->nullable();
            $table->json('settings')->nullable();
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });

        $now = now();
        DB::table('meeting_types')->insert([
            ['key' => 'sprint_planning', 'name' => 'برنامه‌ریزی اسپرینت', 'default_title' => 'جلسه برنامه‌ریزی اسپرینت', 'suggested_duration' => 90, 'agenda_template' => "هدف اسپرینت\nظرفیت تیم\nانتخاب اقلام بک‌لاگ\nریسک‌ها و وابستگی‌ها", 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'daily_standup', 'name' => 'جلسه روزانه', 'default_title' => 'Daily Stand-up', 'suggested_duration' => 15, 'agenda_template' => "کارهای انجام‌شده\nبرنامه امروز\nموانع و نیاز به کمک", 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => json_encode(['frequency' => 'weekdays', 'until' => 'sprint_end']), 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'backlog_refinement', 'name' => 'پالایش بک‌لاگ', 'default_title' => 'پالایش بک‌لاگ', 'suggested_duration' => 60, 'agenda_template' => null, 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'sprint_review', 'name' => 'بازبینی اسپرینت', 'default_title' => 'Sprint Review', 'suggested_duration' => 60, 'agenda_template' => null, 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'sprint_retrospective', 'name' => 'بازنگری اسپرینت', 'default_title' => 'Sprint Retrospective', 'suggested_duration' => 60, 'agenda_template' => null, 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'adhoc', 'name' => 'جلسه موردی اسپرینت', 'default_title' => 'جلسه موردی', 'suggested_duration' => 30, 'agenda_template' => null, 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'blocker_resolution', 'name' => 'رفع مانع', 'default_title' => 'جلسه رفع مانع', 'suggested_duration' => 30, 'agenda_template' => null, 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
            ['key' => 'scope_change', 'name' => 'تغییر محدوده', 'default_title' => 'بررسی تغییر محدوده', 'suggested_duration' => 45, 'agenda_template' => null, 'minutes_template' => null, 'participant_roles' => null, 'recurrence_rule' => null, 'settings' => null, 'is_active' => true, 'created_at' => $now, 'updated_at' => $now],
        ]);

        Schema::table('meetings', function (Blueprint $table) {
            $table->foreignId('sprint_id')->nullable()->after('project_id')->constrained()->nullOnDelete();
            $table->foreignId('meeting_type_id')->nullable()->after('sprint_id')->constrained()->nullOnDelete();
            $table->foreignId('owner_id')->nullable()->after('created_by')->constrained('users')->nullOnDelete();
            $table->foreignId('facilitator_id')->nullable()->after('owner_id')->constrained('users')->nullOnDelete();
            $table->string('status')->default('scheduled')->after('meeting_type');
            $table->text('objective')->nullable()->after('status');
            $table->text('summary')->nullable()->after('notes');
            $table->unsignedSmallInteger('reminder_minutes')->nullable()->after('summary');
            $table->json('recurrence_rule')->nullable()->after('reminder_minutes');
            $table->timestamp('started_at')->nullable()->after('recurrence_rule');
            $table->timestamp('completed_at')->nullable()->after('started_at');
            $table->index(['sprint_id', 'date']);
            $table->index(['status', 'date']);
        });

        Schema::create('meeting_relations', function (Blueprint $table) {
            $table->id();
            $table->foreignId('meeting_id')->constrained()->cascadeOnDelete();
            $table->string('related_type');
            $table->unsignedBigInteger('related_id');
            $table->string('relation_type')->default('related');
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->unique(['meeting_id', 'related_type', 'related_id', 'relation_type'], 'meeting_relation_unique');
            $table->index(['related_type', 'related_id']);
        });

        Schema::create('decisions', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description')->nullable();
            $table->string('status')->default('proposed');
            $table->string('decision_type')->nullable();
            $table->foreignId('project_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('sprint_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('meeting_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('owner_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('decision_maker_id')->nullable()->constrained('users')->nullOnDelete();
            $table->text('rationale')->nullable();
            $table->text('impact')->nullable();
            $table->date('effective_date')->nullable();
            $table->date('review_date')->nullable();
            $table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('action_items', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description')->nullable();
            $table->string('status')->default('open');
            $table->string('priority')->default('medium');
            $table->foreignId('owner_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('project_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('sprint_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('meeting_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('decision_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('converted_to_task_id')->nullable()->constrained('tasks')->nullOnDelete();
            $table->date('due_date')->nullable();
            $table->text('completion_notes')->nullable();
            $table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
            $table->timestamps();
            $table->softDeletes();
            $table->index(['status', 'due_date']);
        });

        Schema::create('blockers', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description')->nullable();
            $table->string('severity')->default('medium');
            $table->string('status')->default('open');
            $table->foreignId('owner_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('raised_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('project_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('sprint_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('meeting_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('task_id')->nullable()->constrained()->nullOnDelete();
            $table->date('due_date')->nullable();
            $table->text('resolution')->nullable();
            $table->timestamp('resolved_at')->nullable();
            $table->timestamps();
            $table->softDeletes();
            $table->index(['status', 'severity']);
        });

        Schema::create('sprint_scope_changes', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sprint_id')->constrained()->cascadeOnDelete();
            $table->foreignId('meeting_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('task_id')->nullable()->constrained()->nullOnDelete();
            $table->string('change_type');
            $table->json('previous_state')->nullable();
            $table->json('new_state')->nullable();
            $table->text('reason')->nullable();
            $table->foreignId('requested_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
            $table->decimal('capacity_impact', 8, 2)->nullable();
            $table->text('goal_impact')->nullable();
            $table->timestamps();
        });

        Schema::table('notifications', function (Blueprint $table) {
            $table->timestamp('archived_at')->nullable()->after('dismissed_at')->index();
            $table->softDeletes();
        });

        if (Schema::hasTable('settings')) {
            DB::table('settings')->insertOrIgnore([
                ['key' => 'working_days', 'value' => json_encode(['saturday', 'sunday', 'monday', 'tuesday', 'wednesday']), 'group' => 'calendar', 'type' => 'list', 'created_at' => $now, 'updated_at' => $now],
                ['key' => 'organization_timezone', 'value' => 'Asia/Tehran', 'group' => 'calendar', 'type' => 'string', 'created_at' => $now, 'updated_at' => $now],
                ['key' => 'default_meeting_reminder_minutes', 'value' => '30', 'group' => 'meeting', 'type' => 'number', 'created_at' => $now, 'updated_at' => $now],
                ['key' => 'meeting_effectiveness_enabled', 'value' => 'true', 'group' => 'meeting', 'type' => 'boolean', 'created_at' => $now, 'updated_at' => $now],
                ['key' => 'sprint_health_override_requires_reason', 'value' => 'true', 'group' => 'sprint', 'type' => 'boolean', 'created_at' => $now, 'updated_at' => $now],
            ]);
        }
    }

    public function down(): void
    {
        Schema::table('notifications', function (Blueprint $table) {
            $table->dropSoftDeletes();
            $table->dropColumn('archived_at');
        });

        Schema::dropIfExists('sprint_scope_changes');
        Schema::dropIfExists('blockers');
        Schema::dropIfExists('action_items');
        Schema::dropIfExists('decisions');
        Schema::dropIfExists('meeting_relations');

        Schema::table('meetings', function (Blueprint $table) {
            $table->dropForeign(['sprint_id']);
            $table->dropForeign(['meeting_type_id']);
            $table->dropForeign(['owner_id']);
            $table->dropForeign(['facilitator_id']);
            $table->dropColumn([
                'sprint_id', 'meeting_type_id', 'owner_id', 'facilitator_id', 'status',
                'objective', 'summary', 'reminder_minutes', 'recurrence_rule',
                'started_at', 'completed_at',
            ]);
        });

        Schema::dropIfExists('meeting_types');
    }
};
