diff --git a/internal/handlers/auth.go b/internal/handlers/auth.go index 64c28fc..e847377 100644 --- a/internal/handlers/auth.go +++ b/internal/handlers/auth.go @@ -903,6 +903,22 @@ func (h *AuthHandler) DeleteUser(c *echo.Context) error { return c.JSON(http.StatusBadRequest, map[string]string{"error": "cannot delete the last admin account"}) } + // If deleting an admin, reassign their libraries and media items to another admin + // before deletion to prevent ON DELETE SET NULL from orphaning ownership + if targetUserRole == "admin" { + successor, err := h.db.GetFirstAdminExclude(c.Request().Context(), targetUserUUID) + if err == nil { + _ = h.db.ReassignLibraries(c.Request().Context(), database.ReassignLibrariesParams{ + CreatedByAdminID: targetUserUUID, + CreatedByAdminID_2: successor.ID, + }) + _ = h.db.ReassignMediaItems(c.Request().Context(), database.ReassignMediaItemsParams{ + AddedByAdminID: targetUserUUID, + AddedByAdminID_2: successor.ID, + }) + } + } + // Delete user (this will cascade to delete all related data) err = h.db.DeleteUser(c.Request().Context(), targetUserUUID) if err != nil {