using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Backend.Migrations
{
    /// <inheritdoc />
    public partial class AddClipCandidateLink : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(
                """
                ALTER TABLE IF EXISTS "ClipSubmissions"
                ADD COLUMN IF NOT EXISTS "CandidateId" integer NULL;

                DO $$
                BEGIN
                    IF to_regclass('"ClipSubmissions"') IS NOT NULL THEN
                        CREATE INDEX IF NOT EXISTS "IX_ClipSubmissions_CandidateId"
                        ON "ClipSubmissions" ("CandidateId");

                        IF NOT EXISTS (
                            SELECT 1
                            FROM pg_constraint
                            WHERE conname = 'FK_ClipSubmissions_Candidates_CandidateId'
                        ) THEN
                            ALTER TABLE "ClipSubmissions"
                            ADD CONSTRAINT "FK_ClipSubmissions_Candidates_CandidateId"
                            FOREIGN KEY ("CandidateId") REFERENCES "Candidates" ("Id")
                            ON DELETE SET NULL;
                        END IF;
                    END IF;
                END $$;
                """);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(
                """
                ALTER TABLE IF EXISTS "ClipSubmissions"
                DROP CONSTRAINT IF EXISTS "FK_ClipSubmissions_Candidates_CandidateId";

                DROP INDEX IF EXISTS "IX_ClipSubmissions_CandidateId";

                ALTER TABLE IF EXISTS "ClipSubmissions"
                DROP COLUMN IF EXISTS "CandidateId";
                """);
        }
    }
}
