using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace JobsMedical.Web.Migrations
{
    /// <inheritdoc />
    public partial class RawListingLinkFks : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_RawListings_Shifts_LinkedShiftId",
                table: "RawListings");

            // LinkedTalentId never had an FK before, so existing rows may point at deleted talent.
            // Null those orphans first, otherwise AddForeignKey below fails on a populated DB.
            migrationBuilder.Sql(
                "UPDATE \"RawListings\" r SET \"LinkedTalentId\" = NULL " +
                "WHERE r.\"LinkedTalentId\" IS NOT NULL " +
                "AND NOT EXISTS (SELECT 1 FROM \"TalentListings\" t WHERE t.\"Id\" = r.\"LinkedTalentId\");");

            migrationBuilder.CreateIndex(
                name: "IX_RawListings_LinkedTalentId",
                table: "RawListings",
                column: "LinkedTalentId");

            migrationBuilder.AddForeignKey(
                name: "FK_RawListings_Shifts_LinkedShiftId",
                table: "RawListings",
                column: "LinkedShiftId",
                principalTable: "Shifts",
                principalColumn: "Id",
                onDelete: ReferentialAction.SetNull);

            migrationBuilder.AddForeignKey(
                name: "FK_RawListings_TalentListings_LinkedTalentId",
                table: "RawListings",
                column: "LinkedTalentId",
                principalTable: "TalentListings",
                principalColumn: "Id",
                onDelete: ReferentialAction.SetNull);
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_RawListings_Shifts_LinkedShiftId",
                table: "RawListings");

            migrationBuilder.DropForeignKey(
                name: "FK_RawListings_TalentListings_LinkedTalentId",
                table: "RawListings");

            migrationBuilder.DropIndex(
                name: "IX_RawListings_LinkedTalentId",
                table: "RawListings");

            migrationBuilder.AddForeignKey(
                name: "FK_RawListings_Shifts_LinkedShiftId",
                table: "RawListings",
                column: "LinkedShiftId",
                principalTable: "Shifts",
                principalColumn: "Id");
        }
    }
}
