<?php

declare(strict_types=1);

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
    {
        // Idempotent: schema.sql already includes this column in migrate:fresh scenarios.
        if (! Schema::hasColumn('projects', 'paused_at')) {
            Schema::table('projects', function (Blueprint $table): void {
                $table->timestampTz('paused_at')->nullable()->after('is_active');
            });
        }
        $indexExists = DB::selectOne(
            "SELECT 1 FROM pg_indexes WHERE tablename='projects' AND indexname='projects_paused_at_idx'"
        );
        if (! $indexExists) {
            Schema::table('projects', function (Blueprint $table): void {
                $table->index('paused_at', 'projects_paused_at_idx');
            });
        }

        // Backfill: для уже paused проектов используем updated_at как best-effort
        // (для долго-paused — grace давно истёк; для свежих — близко к реальной паузе).
        DB::statement(<<<'SQL'
            UPDATE projects
               SET paused_at = updated_at
             WHERE is_active = false
               AND paused_at IS NULL
        SQL);
    }

    public function down(): void
    {
        Schema::table('projects', function (Blueprint $table): void {
            $table->dropIndex('projects_paused_at_idx');
            $table->dropColumn('paused_at');
        });
    }
};
