<?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::table('sprints', function (Blueprint $table) {
            if (! Schema::hasColumn('sprints', 'capacity_hours')) {
                $table->decimal('capacity_hours', 8, 2)->nullable()->after('goal');
            }
            if (! Schema::hasColumn('sprints', 'completed_at')) {
                $table->timestamp('completed_at')->nullable()->after('status');
            }
            if (! Schema::hasColumn('sprints', 'completion_summary')) {
                $table->json('completion_summary')->nullable()->after('completed_at');
            }
        });

        Schema::create('sprint_members', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sprint_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamps();
            $table->unique(['sprint_id', 'user_id']);
        });

        Schema::create('sprint_retrospectives', function (Blueprint $table) {
            $table->id();
            $table->foreignId('sprint_id')->unique()->constrained()->onDelete('cascade');
            $table->text('went_well')->nullable();
            $table->text('problems')->nullable();
            $table->text('improvements')->nullable();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });

        $duplicates = DB::table('sprint_task')
            ->select('sprint_id', 'task_id', DB::raw('MIN(id) as keep_id'))
            ->groupBy('sprint_id', 'task_id')
            ->havingRaw('COUNT(*) > 1')
            ->get();

        foreach ($duplicates as $duplicate) {
            DB::table('sprint_task')
                ->where('sprint_id', $duplicate->sprint_id)
                ->where('task_id', $duplicate->task_id)
                ->where('id', '!=', $duplicate->keep_id)
                ->delete();
        }

        Schema::table('sprint_task', function (Blueprint $table) {
            $table->unique(['sprint_id', 'task_id']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('sprint_retrospectives');
        Schema::dropIfExists('sprint_members');

        Schema::table('sprint_task', function (Blueprint $table) {
            $table->dropUnique(['sprint_id', 'task_id']);
        });

        Schema::table('sprints', function (Blueprint $table) {
            $table->dropColumn(['capacity_hours', 'completed_at', 'completion_summary']);
        });
    }
};
