<?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('backlog_items', function (Blueprint $table) {
            $table->foreignId('converted_to_task_id')
                ->nullable()
                ->after('assigned_sprint_id')
                ->constrained('tasks')
                ->nullOnDelete();
            $table->timestamp('archived_at')->nullable()->after('converted_to_task_id')->index();
        });

        DB::table('backlog_items')
            ->where('status', 'converted')
            ->update(['archived_at' => now()]);

        DB::table('backlog_items')
            ->where('status', '!=', 'converted')
            ->update(['status' => 'active']);

        Schema::table('backlog_items', function (Blueprint $table) {
            $table->string('status')->default('active')->change();
        });
    }

    public function down(): void
    {
        Schema::table('backlog_items', function (Blueprint $table) {
            $table->dropForeign(['converted_to_task_id']);
            $table->dropIndex(['archived_at']);
            $table->dropColumn(['converted_to_task_id', 'archived_at']);
            $table->string('status')->default('new')->change();
        });
    }
};
