using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Watcher.Migrations
{
    /// <inheritdoc />
    public partial class StartServerIdsAtZero : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddCheckConstraint(
                name: "CK_Server_Id",
                table: "Servers",
                sql: "Id >= 0");

            // Bestehende Server-IDs um 1 verringern (1 -> 0, 2 -> 1, etc.)
            migrationBuilder.Sql(@"
                -- Bestehende Server-IDs anpassen, falls Server existieren
                UPDATE Servers SET Id = Id - 1 WHERE EXISTS (SELECT 1 FROM Servers);
                UPDATE Metrics SET ServerId = ServerId - 1 WHERE ServerId IS NOT NULL;
                UPDATE Containers SET ServerId = ServerId - 1 WHERE ServerId IS NOT NULL;

                -- sqlite_sequence anpassen oder initialisieren
                -- Falls Eintrag existiert: seq - 1, ansonsten: INSERT mit seq = -1
                -- Der nächste AUTOINCREMENT wird dann 0 sein
                INSERT OR REPLACE INTO sqlite_sequence (name, seq)
                VALUES ('Servers',
                    COALESCE((SELECT seq - 1 FROM sqlite_sequence WHERE name = 'Servers'), -1)
                );
            ");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropCheckConstraint(
                name: "CK_Server_Id",
                table: "Servers");
        }
    }
}
