using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Nexus.Api.Data;

#nullable disable

namespace Nexus.Api.Migrations
{
    /// <inheritdoc />
    [DbContext(typeof(NexusDbContext))]
    [Migration("20260618233000_AddTaskParentChild")]
    public partial class AddTaskParentChild : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            // This historical migration originally lacked EF discovery
            // metadata. Keep the catch-up operations idempotent so existing
            // installations and fresh PostgreSQL databases converge safely.
            migrationBuilder.Sql(
                """
                ALTER TABLE "Tasks"
                    ADD COLUMN IF NOT EXISTS "ParentTaskId" uuid;

                CREATE INDEX IF NOT EXISTS "IX_Tasks_ParentTaskId"
                    ON "Tasks" ("ParentTaskId");

                DO $$
                BEGIN
                    IF NOT EXISTS (
                        SELECT 1
                        FROM pg_constraint
                        WHERE conname = 'FK_Tasks_Tasks_ParentTaskId'
                          AND conrelid = '"Tasks"'::regclass
                    ) THEN
                        ALTER TABLE "Tasks"
                            ADD CONSTRAINT "FK_Tasks_Tasks_ParentTaskId"
                            FOREIGN KEY ("ParentTaskId")
                            REFERENCES "Tasks" ("Id")
                            ON DELETE SET NULL;
                    END IF;
                END $$;
                """);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(
                """
                ALTER TABLE "Tasks"
                    DROP CONSTRAINT IF EXISTS "FK_Tasks_Tasks_ParentTaskId";
                DROP INDEX IF EXISTS "IX_Tasks_ParentTaskId";
                ALTER TABLE "Tasks"
                    DROP COLUMN IF EXISTS "ParentTaskId";
                """);
        }
    }
}
