using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace OmsorgCore.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class ReplaceOrderStatusWithValueLists : Migration
    {
        // Fest verdrahtete Id für die neue "OrderStatus"-Liste, damit Up/Down deterministisch bleiben.
        private const string OrderStatusListId = "f5793caf-6f5d-4d20-8d27-f0ae9aa43bf5";

        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_orders_order_status_definitions_StatusId",
                table: "orders");

            migrationBuilder.CreateTable(
                name: "value_lists",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uuid", nullable: false),
                    Key = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
                    DisplayName = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_value_lists", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "value_list_items",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uuid", nullable: false),
                    ValueListId = table.Column<Guid>(type: "uuid", nullable: false),
                    Value = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
                    SortOrder = table.Column<int>(type: "integer", nullable: false),
                    IsDefault = table.Column<bool>(type: "boolean", nullable: false),
                    IsInitial = table.Column<bool>(type: "boolean", nullable: false),
                    IsTerminal = table.Column<bool>(type: "boolean", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_value_list_items", x => x.Id);
                    table.ForeignKey(
                        name: "FK_value_list_items_value_lists_ValueListId",
                        column: x => x.ValueListId,
                        principalTable: "value_lists",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "value_list_item_transitions",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uuid", nullable: false),
                    FromItemId = table.Column<Guid>(type: "uuid", nullable: false),
                    ToItemId = table.Column<Guid>(type: "uuid", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_value_list_item_transitions", x => x.Id);
                    table.ForeignKey(
                        name: "FK_value_list_item_transitions_value_list_items_FromItemId",
                        column: x => x.FromItemId,
                        principalTable: "value_list_items",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_value_list_item_transitions_value_list_items_ToItemId",
                        column: x => x.ToItemId,
                        principalTable: "value_list_items",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            // Bestehende Auftragsstatus-Stammdaten 1:1 in die neuen generischen Tabellen übernehmen,
            // MIT IDENTISCHEN Ids - damit orders.StatusId (unverändert) weiterhin auf gültige Zeilen
            // zeigt, ohne dass ein einziger Order-Datensatz angefasst werden muss.
            migrationBuilder.Sql($@"
                INSERT INTO value_lists (""Id"", ""Key"", ""DisplayName"")
                VALUES ('{OrderStatusListId}', 'OrderStatus', 'Auftragsstatus');

                INSERT INTO value_list_items (""Id"", ""ValueListId"", ""Value"", ""SortOrder"", ""IsDefault"", ""IsInitial"", ""IsTerminal"")
                SELECT ""Id"", '{OrderStatusListId}', ""Name"", ""SortOrder"", false, ""IsInitial"", ""IsTerminal""
                FROM order_status_definitions;

                INSERT INTO value_list_item_transitions (""Id"", ""FromItemId"", ""ToItemId"")
                SELECT ""Id"", ""FromStatusId"", ""ToStatusId""
                FROM order_status_transitions;
            ");

            migrationBuilder.DropTable(
                name: "order_status_transitions");

            migrationBuilder.DropTable(
                name: "order_status_definitions");

            migrationBuilder.CreateIndex(
                name: "IX_value_list_item_transitions_FromItemId_ToItemId",
                table: "value_list_item_transitions",
                columns: new[] { "FromItemId", "ToItemId" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_value_list_item_transitions_ToItemId",
                table: "value_list_item_transitions",
                column: "ToItemId");

            migrationBuilder.CreateIndex(
                name: "IX_value_list_items_ValueListId_Value",
                table: "value_list_items",
                columns: new[] { "ValueListId", "Value" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_value_lists_Key",
                table: "value_lists",
                column: "Key",
                unique: true);

            migrationBuilder.AddForeignKey(
                name: "FK_orders_value_list_items_StatusId",
                table: "orders",
                column: "StatusId",
                principalTable: "value_list_items",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);
        }

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

            migrationBuilder.CreateTable(
                name: "order_status_definitions",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uuid", nullable: false),
                    IsInitial = table.Column<bool>(type: "boolean", nullable: false),
                    IsTerminal = table.Column<bool>(type: "boolean", nullable: false),
                    Name = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
                    SortOrder = table.Column<int>(type: "integer", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_order_status_definitions", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "order_status_transitions",
                columns: table => new
                {
                    Id = table.Column<Guid>(type: "uuid", nullable: false),
                    FromStatusId = table.Column<Guid>(type: "uuid", nullable: false),
                    ToStatusId = table.Column<Guid>(type: "uuid", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_order_status_transitions", x => x.Id);
                    table.ForeignKey(
                        name: "FK_order_status_transitions_order_status_definitions_FromStatu~",
                        column: x => x.FromStatusId,
                        principalTable: "order_status_definitions",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                    table.ForeignKey(
                        name: "FK_order_status_transitions_order_status_definitions_ToStatusId",
                        column: x => x.ToStatusId,
                        principalTable: "order_status_definitions",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.Sql($@"
                INSERT INTO order_status_definitions (""Id"", ""Name"", ""SortOrder"", ""IsInitial"", ""IsTerminal"")
                SELECT ""Id"", ""Value"", ""SortOrder"", ""IsInitial"", ""IsTerminal""
                FROM value_list_items
                WHERE ""ValueListId"" = '{OrderStatusListId}';

                INSERT INTO order_status_transitions (""Id"", ""FromStatusId"", ""ToStatusId"")
                SELECT t.""Id"", t.""FromItemId"", t.""ToItemId""
                FROM value_list_item_transitions t
                INNER JOIN value_list_items i ON i.""Id"" = t.""FromItemId""
                WHERE i.""ValueListId"" = '{OrderStatusListId}';
            ");

            migrationBuilder.DropTable(
                name: "value_list_item_transitions");

            migrationBuilder.DropTable(
                name: "value_list_items");

            migrationBuilder.DropTable(
                name: "value_lists");

            migrationBuilder.CreateIndex(
                name: "IX_order_status_definitions_Name",
                table: "order_status_definitions",
                column: "Name",
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_order_status_transitions_FromStatusId_ToStatusId",
                table: "order_status_transitions",
                columns: new[] { "FromStatusId", "ToStatusId" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "IX_order_status_transitions_ToStatusId",
                table: "order_status_transitions",
                column: "ToStatusId");

            migrationBuilder.AddForeignKey(
                name: "FK_orders_order_status_definitions_StatusId",
                table: "orders",
                column: "StatusId",
                principalTable: "order_status_definitions",
                principalColumn: "Id",
                onDelete: ReferentialAction.Restrict);
        }
    }
}
